InfrastructureVol. 6 · Part VI
0 / 0

Shelves / Infrastructure

IN·82

Reverse Proxies and Gateways

The servers in front of your servers: forward versus reverse proxies, L4 versus L7, NGINX's event-driven architecture and configuration, HAProxy's model, Envoy's listeners, clusters and xDS control plane, Caddy and Traefik; TLS termination, re-encryption and passthrough (SNI, ALPN, mTLS, certificates via ACME); routing by host, path and header; load-balancing algorithms; retries and timeouts done safely; compression; header handling (X-Forwarded-*, Forwarded, hop-by-hop, security headers); rate limiting; health checks; and API gateways versus service meshes.

33 topics · ~23 min read · 30-question quiz
Updated Suggest a correction

Start here: one front door for many services

What a reverse proxy is for

Users shouldn't connect to your application processes directly. A reverse proxy accepts every client connection on the public side and forwards each request to a backend on the private side. Being in that position lets it do jobs every service would otherwise repeat:

  • Terminate TLS (hold certificates, speak HTTPS and HTTP/2 or HTTP/3 to clients);
  • Route by host name and path to different services;
  • Load-balance across several instances and stop sending to unhealthy ones;
  • Protect backends with timeouts, size limits, rate limits and buffering of slow clients;
  • Add and clean headers (who the client really was, request IDs), compress responses, cache.

A forward proxy is the opposite: it sits next to clients and forwards their requests outward (a corporate web proxy).

A working configuration

Three tiffin processes: two copies of a "menu" service (ports 9101 and 9102) and one "orders" service (9103). NGINX listens on 8080 for plain HTTP and 8443 for HTTPS:

Nginx
upstream menu   { server 127.0.0.1:9101; server 127.0.0.1:9102; keepalive 16; }
upstream orders { server 127.0.0.1:9103; keepalive 16; }
server {                                   # plain HTTP: only redirects to HTTPS
  listen 8080;
  return 301 https://$host:8443$request_uri;
}
server {
  listen 8443 ssl http2;
  server_name tiffin.local;
  ssl_certificate     /tmp/V6/c82/cert.pem;
  ssl_certificate_key /tmp/V6/c82/key.pem;
  ssl_protocols TLSv1.2 TLSv1.3;
  proxy_http_version 1.1;
  proxy_set_header Connection "";
  proxy_set_header Host              $host;
  proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;
  proxy_set_header X-Request-ID      $request_id;
  location /menu/   { proxy_pass http://menu/; }      # /menu/x → menu's /x
  location /orders/ { proxy_pass http://orders/; }
}
Text
$ curl -si http://tiffin.local:8080/menu/
HTTP/1.1 301 Moved Permanently
$ curl -sk https://tiffin.local:8443/menu/work?ms=0   (four times)
{"port":"9101","host":"vm","slept_ms":0}
{"port":"9102","host":"vm","slept_ms":0}
{"port":"9101","host":"vm","slept_ms":0}
{"port":"9102","host":"vm","slept_ms":0}
$ curl -sk https://tiffin.local:8443/orders/work?ms=0
{"port":"9103","host":"vm","slept_ms":0}
$ curl -skI --http2 https://tiffin.local:8443/menu/healthz
HTTP/2 200
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384

Plain HTTP was redirected to HTTPS; /menu/ requests alternated between the two menu instances (round-robin); /orders/ went to the orders service; clients spoke HTTP/2 over TLS 1.3 while the backends spoke plain HTTP/1.1 on the private side.

What the backend sees

Text
$ curl -sk https://tiffin.local:8443/menu/headers   (what the backend sees)
{
    "User-Agent": "asha-phone",
    "X-Forwarded-For": "127.0.0.1",
    "X-Forwarded-Proto": "https",
    "X-Request-Id": "4a48a2a6a4212cba78be3c9ce751a77a",
    "host": "tiffin.local",
    "path": "/headers",
    "proto": "HTTP/1.1",
    "remote_addr": "127.0.0.1:36498"
}

The TCP connection came from the proxy (remote_addr), so the client's real address and the original scheme travel in X-Forwarded-For and X-Forwarded-Proto (or the standard Forwarded header). Applications must trust these headers only from their own proxies (Spring's server.forward-headers-strategy, Express's trust proxy), or anyone can claim any IP. The request ID lets you join the proxy's access log with the application's logs and traces.

Tool Typical role
NGINX Web server and reverse proxy; static files, TLS, routing; huge install base
HAProxy High-performance TCP/HTTP load balancer with rich health checks and stats
Envoy Programmable proxy configured by API (xDS); the data plane of Istio and many gateways
Caddy, Traefik Automatic HTTPS (ACME), dynamic configuration from Docker/Kubernetes
Cloud load balancers Managed L4/L7 balancing (AWS ALB/NLB, Google Cloud LB, Azure Front Door)

How deep to go in reverse proxies and gateways

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain reverse proxies, TLS termination, routing and load balancing
L2 Configure NGINX/HAProxy/Caddy for HTTPS, routing, headers, timeouts and health checks
L3 Explain balancing algorithms, connection pooling, HTTP/2 and HTTP/3, buffering and retries
L4 Diagnose 502/504s, header and redirect loops, uneven load, connection exhaustion and TLS issues
L5 Design edge, gateway and mesh layers: where TLS, auth, limits and routing live
L6 Operate edge fleets with certificate automation, dynamic config, DDoS defence and observability

What a reverse proxy does

Forward and reverse proxies

  • A forward proxy acts for clients: corporate egress proxies, caching proxies, anonymisers. The client knows it's using a proxy.
  • A reverse proxy acts for servers: clients think they're talking to the origin, but the proxy receives requests and forwards them to one of many upstream (backend) servers.

Almost every production web system has at least one reverse proxy layer. It centralises concerns that every service would otherwise reimplement:

Concern What the proxy does
TLS termination Holds certificates, negotiates TLS 1.3, HTTP/2 and HTTP/3 with clients
Routing Sends api.example.com/orders/* to the orders service, /static/* to object storage
Load balancing Spreads requests across healthy upstream instances
Resilience Timeouts, retries, circuit breaking, outlier ejection
Compression and caching gzip/Brotli/zstd responses; cache static or cacheable content
Security Rate limiting, IP allow/deny lists, WAF rules, request size limits, security headers, hiding upstream details
Observability Access logs, metrics, tracing headers for every request
Protocol translation HTTP/1.1 ↔ HTTP/2, HTTP ↔ gRPC, WebSocket upgrade, HTTP/3 (QUIC) at the edge
client CDN / edgeTLS · WAFcache cloud LBL4 / L7multi-zone gatewayroute · authnrate limit orders ×3(+ sidecar) catalog ×2(+ sidecar) /orders/* → orders/catalog/* → catalog
A typical request path through proxy layers. A CDN or edge network terminates TLS near the user; a cloud load balancer spreads traffic across zones; an ingress gateway (NGINX, Envoy, HAProxy) routes by host and path to service instances, possibly through sidecar proxies in a service mesh.

Layer 4 versus layer 7

  • L4 (transport) proxies forward TCP or UDP connections without understanding the application protocol. They see IPs and ports (and, with TLS, the SNI hostname in the ClientHello if they peek). Fast and protocol-agnostic: databases, MQTT, raw TCP, TLS passthrough. Examples: AWS NLB, HAProxy mode tcp, NGINX stream, Envoy TCP proxy, IPVS, eBPF load balancers (Cilium, Katran).
  • L7 (application) proxies parse HTTP (or gRPC, etc.): they can route by host, path and headers, rewrite requests, retry individual requests, compress, cache, and balance per request rather than per connection. Examples: NGINX http, HAProxy mode http, Envoy HTTP connection manager, AWS ALB, Traefik, Caddy.

Per-request balancing matters for HTTP/2 and gRPC: they multiplex many requests over one long-lived connection, so an L4 balancer pins all of a client's traffic to one backend. Use an L7 proxy or client-side balancing for gRPC.

NGINX

Architecture

NGINX (2004, Igor Sysoev; now F5) was built for the C10k problem: thousands of concurrent connections. A master process reads configuration and manages worker processes (usually one per CPU core). Each worker runs a single-threaded event loop over epoll, handling thousands of non-blocking connections, rather than a thread per connection. Reloading configuration (nginx -s reload) starts new workers with the new config while old workers finish their in-flight requests: zero-downtime reloads.

Variants: open-source NGINX, NGINX Plus (commercial: active health checks, dynamic upstream API, more metrics), OpenResty (NGINX + LuaJIT), Angie (a fork by former NGINX developers), and freenginx.

Configuration model

Configuration is a tree of contexts: main → events, http → server (virtual hosts, matched by listen and server_name) → location (matched by URI). Separately, stream handles L4.

location matching order matters:

  1. location = /exact (exact match) wins immediately.
  2. Otherwise the longest prefix match is remembered; if it's ^~, use it and skip regexes.
  3. Regex locations (~ case-sensitive, ~* insensitive) are checked in file order; the first match wins.
  4. If none match, use the remembered longest prefix.
Nginx
# /etc/nginx/conf.d/api.conf: TLS termination, routing, load balancing, headers, limits
upstream orders {
    zone orders 64k;
    least_conn;                                      # or round-robin (default), ip_hash, hash $key consistent
    server 10.0.1.11:8080 max_fails=3 fail_timeout=10s;
    server 10.0.1.12:8080 max_fails=3 fail_timeout=10s;
    server 10.0.1.13:8080 backup;
    keepalive 64;                                    # pool of idle upstream connections
}

limit_req_zone $binary_remote_addr zone=perip:10m rate=20r/s;

server {
    listen 80;
    server_name api.example.com;
    return 308 https://$host$request_uri;            # force HTTPS
}

server {
    listen 443 ssl;
    listen 443 quic reuseport;                       # HTTP/3
    http2 on;
    server_name api.example.com;

    ssl_certificate     /etc/ssl/api/fullchain.pem;
    ssl_certificate_key /etc/ssl/api/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    add_header Alt-Svc 'h3=":443"; ma=86400' always;
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;

    client_max_body_size 10m;
    gzip on; gzip_types application/json text/css application/javascript;

    location /orders/ {
        limit_req zone=perip burst=40 nodelay;
        proxy_pass http://orders;                    # no URI part: forwards /orders/... unchanged
        proxy_http_version 1.1;
        proxy_set_header Connection "";              # enable upstream keepalive
        proxy_set_header Host              $host;
        proxy_set_header X-Real-IP         $remote_addr;
        proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Request-ID      $request_id;
        proxy_connect_timeout 2s;
        proxy_read_timeout    30s;
        proxy_next_upstream error timeout http_502 http_503;   # retry on another server…
        proxy_next_upstream_tries 2;                            # …at most once more
    }

    location /ws/ {                                  # WebSocket upgrade
        proxy_pass http://orders;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 1h;
    }

    location /static/ {
        root /var/www;
        expires 7d;
        add_header Cache-Control "public, immutable";
    }
}

A classic trap: proxy_pass http://orders/; (with a trailing slash/URI) replaces the matched location prefix, while proxy_pass http://orders; passes the URI unchanged. add_header in a nested block discards all add_header directives inherited from the parent unless repeated.

nginx -t validates configuration; always run it before reloading.

HAProxy

HAProxy (2000, Willy Tarreau) is a high-performance L4/L7 load balancer known for reliability, rich load-balancing features and observability. Its model:

  • frontend: where clients connect (bind address, TLS, ACLs, routing rules).
  • backend: a pool of servers with a balancing algorithm, health checks and per-server settings.
  • ACLs: named conditions (acl is_api path_beg /api) used in use_backend, http-request deny, etc.
  • Stick tables: in-memory key-value tables for rate limiting, connection tracking and session persistence (counting requests per IP over a sliding window), shareable between peers.
  • Runtime API (socat to a stats socket) to drain servers, change weights, and read stats without reloads; hitless reloads with socket transfer.
HAProxy
# /etc/haproxy/haproxy.cfg
global
    maxconn 50000
defaults
    mode http
    timeout connect 2s
    timeout client  30s
    timeout server  30s
    option httplog
    option forwardfor                                   # adds X-Forwarded-For

frontend fe_https
    bind :443 ssl crt /etc/haproxy/certs/ alpn h2,http/1.1
    http-request set-header X-Forwarded-Proto https
    # Rate limit: 100 requests / 10 s per source IP
    stick-table type ip size 1m expire 1m store http_req_rate(10s)
    http-request track-sc0 src
    http-request deny deny_status 429 if { sc_http_req_rate(0) gt 100 }
    acl is_orders path_beg /orders
    use_backend be_orders if is_orders
    default_backend be_web

backend be_orders
    balance leastconn
    option httpchk GET /healthz
    http-check expect status 200
    retry-on conn-failure empty-response 503
    retries 2
    server o1 10.0.1.11:8080 check inter 2s fall 3 rise 2
    server o2 10.0.1.12:8080 check inter 2s fall 3 rise 2

backend be_web
    server w1 10.0.2.21:8080 check

Envoy

Model

Envoy (Lyft, 2016; CNCF graduated) is an L4/L7 proxy designed for service-oriented architectures and dynamic configuration. It's the data plane of Istio, Envoy Gateway, Contour, Emissary, Gloo, AWS App Mesh (retired) and others, and widely used as an edge proxy.

Core concepts:

Concept Meaning
Listener An address/port Envoy accepts connections on, with a chain of network filters
HTTP connection manager The L7 network filter; runs HTTP filters (router, rate limit, ext_authz, JWT authn, CORS, Lua/Wasm…)
Route configuration Virtual hosts and routes: match on host, path, headers → cluster, with per-route timeouts and retry policies
Cluster A group of upstream endpoints with a load-balancing policy, health checks, circuit breakers, outlier detection, TLS settings
Endpoint An upstream host:port

xDS: Envoy's dynamic configuration APIs (LDS listeners, RDS routes, CDS clusters, EDS endpoints, SDS secrets, aggregated as ADS) let a control plane (Istio's istiod, Envoy Gateway, a custom go-control-plane server) push configuration changes without restarts. That's why Envoy fits Kubernetes, where endpoints change constantly. xDS is also used by gRPC clients for proxyless service mesh.

Strengths: first-class HTTP/2, gRPC, HTTP/3; outlier detection (eject hosts with consecutive 5xx); circuit breakers (max connections, pending requests, retries per cluster); retry budgets; rich stats and tracing; extensibility via Wasm and Lua filters.

YAML
# Envoy static config fragment: a route with per-try timeout, retry policy and a cluster with outlier detection
route_config:
  virtual_hosts:
  - name: api
    domains: ["api.example.com"]
    routes:
    - match: { prefix: "/orders/" }
      route:
        cluster: orders
        timeout: 5s
        retry_policy:
          retry_on: "connect-failure,refused-stream,unavailable,503"
          num_retries: 2
          per_try_timeout: 1.5s
          retry_back_off: { base_interval: 0.05s, max_interval: 0.5s }
clusters:
- name: orders
  type: STRICT_DNS
  lb_policy: LEAST_REQUEST
  load_assignment:
    cluster_name: orders
    endpoints: [{ lb_endpoints: [{ endpoint: { address: { socket_address: { address: orders.internal, port_value: 8080 } } } }] }]
  circuit_breakers:
    thresholds: [{ max_connections: 1000, max_pending_requests: 500, max_retries: 3 }]
  outlier_detection:
    consecutive_5xx: 5
    interval: 10s
    base_ejection_time: 30s
    max_ejection_percent: 50

Caddy and Traefik

  • Caddy (Go): automatic HTTPS by default (obtains and renews certificates via ACME from Let's Encrypt or ZeroSSL), HTTP/3, a very short config language (Caddyfile) plus a JSON API. Great for small deployments and internal tools.
  • Traefik (Go): configuration discovered dynamically from Docker labels, Kubernetes (Ingress, Gateway API, CRDs), Consul; automatic ACME; popular with Docker Compose and small Kubernetes clusters.
Caddyfile
# Caddyfile: HTTPS certificate obtained and renewed automatically
api.example.com {
    encode zstd gzip
    reverse_proxy /orders/* 10.0.1.11:8080 10.0.1.12:8080 {
        lb_policy least_conn
        health_uri /healthz
    }
}

TLS at the proxy

Termination, re-encryption, passthrough

termination client proxy backend TLS HTTP re-encryption client proxy backend TLS TLS / mTLS passthrough client L4 proxy backend TLS end to end (opaque to proxy) routes on SNI only; can't see HTTP
Three TLS modes. Termination decrypts at the proxy and forwards plain HTTP inside the network; re-encryption decrypts, inspects and opens a new TLS connection to the backend; passthrough forwards the encrypted bytes untouched, routing only on the SNI hostname.
Mode Pros Cons
Termination Proxy can route on HTTP, compress, cache, add headers; certificates in one place Plain text inside the network; zero-trust and compliance often require encryption in transit everywhere
Re-encryption Full L7 features and encryption to backends (often mTLS, giving service identity) Certificates needed on backends too; CPU cost (minor with modern hardware)
Passthrough End-to-end encryption; backend holds the only key Proxy can't see HTTP: no path routing, no header manipulation, no per-request retries

TLS details proxies handle

  • SNI (Server Name Indication): the client sends the hostname in the ClientHello, so one IP can serve many certificates. Encrypted Client Hello (ECH) hides it from observers and is being deployed by browsers and CDNs.
  • ALPN negotiates the application protocol (h2, http/1.1) during the handshake; HTTP/3 is advertised with Alt-Svc and runs over QUIC (UDP 443).
  • TLS 1.3 only, or 1.2 + 1.3 with modern cipher suites; disable older versions. Use OCSP stapling where still relevant, and HSTS.
  • Post-quantum hybrid key exchange (X25519MLKEM768) is now on by default in major browsers, OpenSSL 3.5+ and Go 1.24+, and is coming to the JDK's TLS stack; make sure proxies are new enough to negotiate it.
  • Certificates: automate issuance and renewal via ACME (Let's Encrypt, ZeroSSL, Google Trust Services) with cert-manager (Kubernetes), Caddy, Traefik, certbot. Public TLS certificate maximum lifetimes are shrinking (CA/Browser Forum ballot: 200 days from March 2026, 100 days from 2027, 47 days by 2029), so manual renewal is no longer viable.
  • mTLS: the proxy also verifies the client's certificate: for service-to-service identity (service mesh), partner APIs, or devices. The proxy passes the verified identity upstream in a header (e.g. X-Forwarded-Client-Cert in Envoy), which backends must only trust from the proxy.

Routing

L7 proxies route on any combination of:

  • Host (virtual hosting): api.example.com vs www.example.com.
  • Path prefix, exact or regex: /orders/, /v2/.
  • Headers: X-Canary: true, Accept-Version, user-agent, cookies (for canary or A/B routing, chapter 84).
  • Method, query parameters, client IP, mTLS identity.
  • Weights: send 5% of /orders/ to v2 (traffic splitting).

Rewrites adjust the path before forwarding (strip /api prefix), redirect (301/308 permanent, 302/307 temporary; 307/308 preserve the method and body), or return fixed responses (maintenance pages, 410 Gone).

Load balancing

Algorithm How Good for
Round robin (weighted) Rotate through servers, optionally by weight Homogeneous servers, similar request costs
Least connections / least request Pick the server with fewest active requests Varying request durations; long-lived connections
Power of two choices (P2C) Pick 2 servers at random; send to the less loaded Near-optimal balance with no global state; Envoy's LEAST_REQUEST default, NGINX random two least_conn
EWMA / latency-aware Prefer servers with lower recent latency (peak EWMA, used by Linkerd and Finagle) Heterogeneous or degrading backends
IP hash / consistent hash Hash client IP, header or cookie onto a ring (ketama, Maglev, ring hash) Session affinity, cache locality (same key → same cache node); consistent hashing moves few keys when servers change
Random Uniform random Simple, surprisingly good with many clients

Related settings:

  • Health checks: active (proxy probes /healthz every N seconds, marks down after fall failures, up after rise successes) and passive (watch real responses: consecutive errors or timeouts eject a host temporarily = outlier detection). Cap ejections (max_ejection_percent) so a widespread failure doesn't eject everything.
  • Slow start: ramp traffic to newly added hosts gradually (cold caches, JIT warm-up).
  • Session affinity (sticky sessions): by cookie or hash. It ties users to instances and complicates scaling and deployments; prefer stateless services with shared session stores.
  • Connection pooling / keepalive to upstreams: reuse TCP and TLS connections; without it, each request pays a handshake and you can run out of ephemeral ports.
  • Draining: when removing a server, stop new requests but let in-flight ones finish (HAProxy set server state drain, Kubernetes endpoint termination, chapter 84).

Timeouts and retries at the proxy

A proxy is the natural place for resilience policy, and the easiest place to cause a retry storm (chapter 78):

  • Timeouts at every stage: connect (short, ~1–2 s), per-try / upstream response, overall request, idle (keepalive), and client body/header read timeouts (slow-client attacks like Slowloris).
  • Timeout budget ordering: the edge's timeout should exceed the gateway's, which should exceed the service's, so the inner layer fails first with a meaningful error rather than everyone timing out at once.
  • Retry only safe cases:
  • connection failures and refused streams (the request didn't reach the app);
  • 502/503/504 for idempotent methods or requests with idempotency keys;
  • never automatically retry non-idempotent POSTs after the request was sent, unless keys make them safe (chapter 74).
  • Bound retries: 1–2 retries, with a retry budget (Envoy: retry_budget as a percentage of active requests), backoff with jitter, and per-try timeouts so the total stays within the overall timeout.
  • Hedging (send a duplicate after a delay) only for idempotent, latency-critical reads.

Compression

  • Compress text responses (JSON, HTML, CSS, JS, SVG) at the proxy: gzip (universal), Brotli (br, better ratios, widely supported), zstd (supported by Chrome and Firefox since 2024; fast). Negotiated with Accept-Encoding / Content-Encoding; add Vary: Accept-Encoding for caches.
  • Don't compress already-compressed content (images, video, archives) or tiny responses (below ~1 KB).
  • Pre-compress static assets at build time (.br, .gz files) and serve them directly (gzip_static, brotli_static).
  • Security: compression combined with secrets reflected next to attacker-controlled input over TLS enables BREACH-style attacks; avoid compressing responses that mix secrets (CSRF tokens) with user input, or mask the tokens.

Headers

Forwarding information

Behind a proxy, the backend sees the proxy's IP and scheme. Proxies add:

Header Meaning
X-Forwarded-For: client, proxy1, proxy2 Chain of client and proxy IPs (each proxy appends the address it received from)
X-Forwarded-Proto: https Original scheme
X-Forwarded-Host Original Host header
X-Real-IP Single client IP (NGINX convention)
Forwarded: for=203.0.113.7;proto=https;host=api.example.com Standard form (RFC 7239) of the above
PROXY protocol (v1 text / v2 binary) For L4 proxies: prepends the original client address to the TCP stream, since there are no HTTP headers to add (AWS NLB, HAProxy)

Trust rules: these headers are client-controlled unless your proxy overwrites them. The backend must take the client IP only from the rightmost entries added by proxies you trust (configure trusted proxy IPs: Spring's server.forward-headers-strategy=native/Tomcat RemoteIpValve, Express trust proxy, Go's X-Forwarded-For parsing via middleware with an allowlist, NGINX set_real_ip_from + real_ip_header). Otherwise attackers spoof IPs to bypass rate limits and IP allowlists.

Hop-by-hop and request IDs

  • Hop-by-hop headers (Connection, Keep-Alive, Transfer-Encoding, Upgrade, TE, Proxy-Authorization) apply to one connection and must not be forwarded; proxies strip them. Inconsistent parsing of Content-Length vs Transfer-Encoding between proxy and backend causes HTTP request smuggling: keep proxies updated and normalise or reject ambiguous requests.
  • Request IDs / tracing: generate X-Request-ID (or W3C traceparent) at the edge if absent, and log it everywhere (Vol. 9).
  • Host header: pass the original (proxy_set_header Host $host) if backends build absolute URLs; validate against expected hosts to avoid Host-header injection.

Security headers at the edge

The proxy is a convenient place to add response headers consistently:

  • Strict-Transport-Security (HSTS)
  • Content-Security-Policy
  • X-Content-Type-Options: nosniff
  • Referrer-Policy
  • Permissions-Policy
  • frame-ancestors (or X-Frame-Options)

It should also remove headers that leak internals: Server version details, X-Powered-By, upstream error pages.

Rate limiting at the proxy

Chapter 76 covered algorithms; at the proxy:

  • NGINX: limit_req (leaky bucket with burst, nodelay), limit_conn (concurrent connections per key), keyed by IP, API key header or any variable; state is per instance unless you use NGINX Plus zone sync.
  • HAProxy: stick tables with http_req_rate, conn_cur, shareable via peers.
  • Envoy: local rate limit filter (token bucket per instance) and global rate limit via an external gRPC rate-limit service backed by Redis, with descriptors (remote_address, header: x-api-key, path).
  • Gateways add per-consumer plans and quotas (Kong, Apigee, AWS API Gateway).

Return 429 with Retry-After, exempt health checks, and key on authenticated identity where possible (IPs are shared behind NAT and rotated by attackers).

Gateways and meshes

API gateways

An API gateway is a reverse proxy with API-management features: authentication (JWT validation, OAuth2 introspection, API keys), authorisation hooks, per-consumer rate limits and quotas, request/response transformation, API versioning, developer portals, analytics and monetisation. Examples: Kong (NGINX/OpenResty-based), Apigee, AWS API Gateway, Azure API Management, Tyk, KrakenD, Spring Cloud Gateway (Java, reactive), Envoy Gateway, and AI gateways that route and meter LLM API calls.

Avoid putting business logic in the gateway (it becomes a shared bottleneck owned by no one). Backend-for-frontend (BFF) services are a better place for client-specific aggregation.

Kubernetes ingress and Gateway API

In Kubernetes, the edge proxy is configured by Kubernetes objects:

  • Ingress (older API): host/path rules with controller-specific annotations for everything else. The community Ingress NGINX controller was retired in March 2026 (no further releases or security fixes); migrate to another Ingress controller or, preferably, to the Gateway API.
  • Gateway API: role-oriented resources (GatewayClass for infrastructure providers, Gateway for cluster operators, HTTPRoute/GRPCRoute/TLSRoute for application teams), with traffic splitting, header matching and cross-namespace delegation in the spec rather than annotations. Implemented by Envoy Gateway, Istio, Cilium, NGINX Gateway Fabric, Kong, Traefik, HAProxy, and cloud load balancers (GKE, AWS Load Balancer Controller, Azure). Chapter 83 shows examples.

Service mesh

A service mesh applies proxy features to east-west (service-to-service) traffic:

  • Sidecar model: an Envoy proxy next to every pod intercepts traffic (Istio's classic mode, Linkerd with its Rust micro-proxy linkerd2-proxy).
  • Sidecar-less: Istio ambient mode (a per-node L4 ztunnel in Rust for mTLS, plus optional per-namespace L7 "waypoint" Envoys); Cilium service mesh using eBPF plus per-node Envoy.
  • Features: automatic mTLS and workload identity (SPIFFE IDs), retries/timeouts/circuit breaking per route, traffic splitting for canaries, authorisation policies, uniform telemetry.
  • Costs: operational complexity, extra latency per hop (sub-millisecond to a few ms), resource overhead, and debugging through another layer. Adopt when you have many services and need uniform mTLS and traffic policy; small systems often do fine with libraries and an ingress gateway.

Lab: load balancing, health, pooling and timeouts

HAProxy 2.8 and NGINX 1.24 on the volume's 2-CPU VM, tiffin backends (with /work?ms=N simulating N ms of work), Toxiproxy to make one backend slow, and wrk as the load generator. Everything shares two CPUs, so absolute throughput is modest; the comparisons are what matter.

Experiment 1: round-robin versus least connections with one slow backend

Three backends; Toxiproxy adds 200 ms to every response from backend 3. 30 connections for 10 seconds, 5 ms of work per request:

Text
roundrobin: 412.01 req/s, p50 12.79ms, p99 208.22ms
leastconn:  3285.23 req/s, p50 6.25ms, p99 206.27ms

Round-robin kept sending a third of requests to the slow backend, so connections piled up there and throughput collapsed to an eighth. Least-connections noticed that backend 3 always had requests outstanding and sent it far fewer: throughput 8× higher and the median back to normal (the p99 still includes the slow backend's occasional requests). With uniform, fast requests the algorithms hardly differ; with uneven backends or request costs, load-aware algorithms (least connections, Envoy's least request with power of two choices, EWMA latency in Linkerd and Finagle) matter a lot. Better still: remove the slow instance (outlier detection).

Experiment 2: a backend dies mid-run

Three healthy backends; one is killed 3 seconds into a 10-second run with 20 connections:

Text
no health checks:                        999.93 req/s, non-2xx 40, socket timeouts 40
health checks every 500 ms + redispatch: 3240.77 req/s, non-2xx 0

Without health checks, HAProxy kept routing to the dead backend: those requests failed with 503s after connection retries, and others timed out. With active checks (option httpchk GET /healthz, check inter 500ms fall 2), the server was marked down within about a second, and option redispatch with retries 2 moved the few in-flight failures to other servers. Health checks should hit an endpoint that reflects the instance's ability to serve (chapter 78's gray failures), and passive checks (counting real request failures) complement active ones.

Experiment 3: keep-alive between the proxy and backends

wrk → NGINX → one backend, 20 connections, 8 seconds:

Text
upstream keep-alive off: 15037.56 req/s, new TIME_WAIT sockets: 16745
upstream keep-alive on:  33426.09 req/s, new TIME_WAIT sockets: 217

By default NGINX opens a new connection to the backend for every request (HTTP/1.0 semantics). Reusing connections (keepalive 32 in the upstream plus proxy_http_version 1.1 and an empty Connection header) more than doubled throughput and avoided 16,000 sockets lingering in TIME_WAIT (chapter 79). With TLS to the backends the difference is far larger, because each new connection also costs a handshake.

Experiment 4: compression and timeouts

Text
/menu.json without gzip: 20449 bytes; with gzip: 1934 bytes
backend takes 3 s, proxy_read_timeout 1s: HTTP 504 after 1.001685 s

Gzip shrank a 20 KB JSON menu tenfold (Brotli usually does a little better for text); compress text types at the proxy or the app, never already-compressed images. The read timeout turned a 3-second backend response into a 504 Gateway Timeout after 1 second. Proxy timeouts must be consistent with the layers around them: shorter than the client's (or the client gives up first and the work is wasted), longer than the backend's own deadline, and retries at the proxy only for idempotent requests (NGINX's proxy_next_upstream doesn't retry non-idempotent methods by default since 1.9.13).

Try it yourself

  1. Repeat experiment 1 with HAProxy's balance random(2) (power of two choices) and with server … weight.
  2. Add limit_req_zone/limit_req to NGINX and measure 429/503 responses under wrk (chapter 76).
  3. Turn on HAProxy's stats page and Prometheus exporter and watch backend states during experiment 2.
  4. Put Envoy in front of the same backends with outlier detection (consecutive_5xx) and compare with experiment 2.

Revision sheet: reverse proxies and gateways

Key ideas

  • Roles: TLS termination, routing (host, path, header), load balancing, health checks, timeouts and limits, buffering, compression, caching, header management, auth offload, WAF.
  • NGINX: server/location matching, upstream, proxy_pass path rules, proxy_set_header, keepalive, buffering, limit_req, proxy_next_upstream.
  • HAProxy: frontends/backends, ACLs, balance algorithms, active/passive checks, stick tables, stats, runtime API.
  • Envoy: listeners, filter chains, clusters, xDS dynamic configuration, outlier detection, retries with budgets, observability; Istio, Envoy Gateway.
  • TLS: certificates and chains, SNI, TLS 1.3, ACME/Let's Encrypt automation, HSTS, mTLS to backends, OCSP stapling.
  • Load balancing: round-robin, weighted, least connections/requests, power of two choices, consistent hashing for affinity, L4 vs L7.
  • Timeouts and retries: connect/read/idle timeouts aligned across layers; retry only idempotent requests; retry budgets.
  • Gateways and meshes: API gateways (auth, quotas, transformation), Kubernetes Gateway API, service meshes (sidecars or ambient).

Numbers to remember

  • Lab: leastconn gave 8× round-robin's throughput with one 200 ms backend; health checks removed 40 errors and 40 timeouts when a backend died; upstream keep-alive doubled throughput and cut TIME_WAIT from 16,745 to 217; gzip cut a 20 KB JSON to 1.9 KB; a 1 s read timeout returned 504 in 1.0 s.

Pitfalls

  • No upstream keep-alive.
  • Trusting forwarded headers from the internet.
  • Retrying POSTs at the proxy.
  • Timeouts longer at the proxy than at the client.
  • Health checks that always return 200.
  • Forgetting WebSocket/streaming settings (upgrade headers, buffering, idle timeouts).

Glossary

  • Upstream / backend: servers the proxy forwards to.
  • SNI: TLS extension carrying the requested host name.
  • L4 / L7 balancing: by connection (TCP) vs by request (HTTP).
  • 502 / 504: bad gateway (backend error/refused) / gateway timeout.
  • Outlier detection: ejecting hosts with abnormal errors or latency.
  • xDS: Envoy's discovery APIs for dynamic configuration.