TExcelTAD
Home › Web Servers in Depth: Nginx, HAProxy, Caddy & Traefik › Field Notes: Proxies in Production

Field Notes: Proxies in Production

Practical lessons from running front doors, grouped by the mistake they prevent. Most of them were learned during an incident.

Nginx resolves hostnames once, at startup

proxy_pass http://app.internal:9000; and server app.internal:9000; in an upstream are resolved when the configuration is loaded, with the system resolver, and never again. Two consequences, both shown below with a local DNS server (dnsmasq):

  1. If the name doesn't resolve at that moment, Nginx refuses to start (or to reload): a DNS hiccup during a deploy takes the proxy down.
  2. If the address behind the name changes later (a cloud load balancer, a container that was rescheduled, a database failover), Nginx keeps sending traffic to the old address until the next reload.

The fix is a resolver and a variable in proxy_pass, which makes Nginx resolve at request time and respect the TTL (valid= overrides it):

bash · try it yourself
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers(); self.wfile.write(f"{sys.argv[2]}\n".encode())
    def log_message(self, *a): pass
HTTPServer((sys.argv[1], 9000), H).serve_forever()
EOF
python3 app.py 127.0.0.2 blue & python3 app.py 127.0.0.3 green &       # two "hosts" on loopback addresses
dns() {   # (re)start dnsmasq with app.internal -> $1
  [ -f d.pid ] && kill "$(cat d.pid)" && sleep 0.3
  echo "address=/app.internal/$1" > dns.conf
  dnsmasq --conf-file=dns.conf --port 5353 --listen-address=127.0.0.1 --bind-interfaces --no-resolv --user=learner --pid-file="$PWD/d.pid"
}
dns 127.0.0.2
for i in $(seq 50); do [ -n "$(dig +short @127.0.0.1 -p 5353 app.internal)" ] && break; sleep 0.1; done
echo "DNS says app.internal = $(dig +short @127.0.0.1 -p 5353 app.internal)"
echo "--- 1. a static upstream name, resolved by the system resolver at load time:"
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  upstream app { server app.internal:9000; }
  server { listen 127.0.0.1:8080; location / { proxy_pass http://app; } }
}
EOF
nginx -t -p "$PWD" -c nginx.conf -e stderr 2>&1 | grep emerg | sed 's/.*#[0-9]*: //'
echo "--- 2. resolver + variable: resolved per request, honouring valid=1s:"
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  access_log off;
  resolver 127.0.0.1:5353 valid=1s ipv6=off;
  server {
    listen 127.0.0.1:8080;
    location / {
      set $app_host app.internal;
      proxy_pass http://$app_host:9000;
    }
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
echo "before the DNS change: $(curl -s 127.0.0.1:8080/)"
dns 127.0.0.3
for i in $(seq 50); do [ "$(curl -s 127.0.0.1:8080/)" = green ] && break; sleep 0.2; done   # wait out valid=1s
echo "after the DNS change:  $(curl -s 127.0.0.1:8080/)"
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; kill "$(cat d.pid)" %1 %2
DNS says app.internal = 127.0.0.2
--- 1. a static upstream name, resolved by the system resolver at load time:
host not found in upstream "app.internal:9000" in /home/learner/nginx.conf:5
--- 2. resolver + variable: resolved per request, honouring valid=1s:
before the DNS change: blue
after the DNS change:  green

The static upstream couldn't even be loaded, because the system resolver doesn't know the name (the sandbox has no /etc/hosts entry for it; in production the same happens when DNS is briefly down). With the resolver and a variable, Nginx followed the DNS change without a reload. Caveats: with a variable, proxy_pass no longer replaces the location prefix (the full original URI is passed), ipv6=off avoids AAAA lookups the resolver can't answer, and open-source Nginx 1.27.3+ also supports server … resolve; inside upstream blocks (with a zone) for the same effect with load balancing. HAProxy (resolvers section + server-template), Caddy and Traefik re-resolve on their own.

X-Forwarded-For: trust only what your own proxies added

Every proxy appends the address it received the request from to X-Forwarded-For. The left part of the header comes from the client and can contain anything. Behind a load balancer, the real client is the rightmost address that isn't one of your proxies, which is exactly what the realip module computes with real_ip_recursive on:

bash · try it yourself
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  access_log off;
  map $http_x_forwarded_for $leftmost_xff { "~^(?<first>[^, ]+)" $first; default "-"; }
  set_real_ip_from 127.0.0.1;            # our load balancer (here: whoever connects from loopback)
  set_real_ip_from 10.0.0.0/8;           # our internal proxies
  real_ip_header X-Forwarded-For;
  real_ip_recursive on;
  server {
    listen 127.0.0.1:8080;
    return 200 "remote_addr=$remote_addr   naive leftmost XFF=$leftmost_xff\n";
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
echo "honest client 203.0.113.7, via an internal proxy 10.1.2.3:"
curl -s -H "X-Forwarded-For: 203.0.113.7, 10.1.2.3" 127.0.0.1:8080/
echo "attacker 198.51.100.66 sends a fake header; the load balancer appends the real address:"
curl -s -H "X-Forwarded-For: 1.2.3.4, 198.51.100.66" 127.0.0.1:8080/
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
honest client 203.0.113.7, via an internal proxy 10.1.2.3:
remote_addr=203.0.113.7   naive leftmost XFF=203.0.113.7
attacker 198.51.100.66 sends a fake header; the load balancer appends the real address:
remote_addr=198.51.100.66   naive leftmost XFF=1.2.3.4

$remote_addr became the real client in both cases; the "leftmost entry" that much application code reads was the forged 1.2.3.4. Rate limits, geo-blocking and audit logs keyed on the forged value are worthless. Also: if clients can reach a proxy directly, bypassing the load balancer, they can send a header that looks as if it came from it. Firewall the proxy so only the load balancer can connect, or use the PROXY protocol, which can't be set by HTTP clients.

Timeouts must shrink from the outside in

Client → CDN (100 s) → cloud load balancer (60 s) → Nginx (proxy_read_timeout) → app server → database. Each inner timeout should be shorter than the one outside it; otherwise the outer layer gives up first, returns its own generic error, and the inner layers keep working on a request whose client is gone, holding connections and database locks. Write the chain down once per service, including the app's own request timeout and the database statement timeout.

Random 502s right after deploys or at low traffic

Two classic causes, both about connection reuse (keepalive):

  • The backend closes idle keep-alive connections sooner than the proxy expects, and the proxy reuses one just as it is closed. Make the backend's idle timeout longer than the proxy's upstream keepalive timeout.
  • A deploy kills app processes without draining. Use the proxy's draining (set server … state drain in HAProxy, weight 0 in Traefik) or graceful shutdown in the app (stop accepting, finish in-flight requests, then exit), and wait longer than the longest request.

Health checks that cause outages

  • A deep health check that tests a shared dependency takes every server out at once when that dependency blips. Fail health checks for problems local to the instance; report shared-dependency problems through metrics and alerts.
  • /health behind authentication, rate limits or a WAF fails for the wrong reasons. Exempt it explicitly, and keep it cheap.

Certificates expire on weekends

Automate renewal (ACME), but also monitor the certificate actually served, from outside, for every name and every port, as Renewal & Expiry Monitoring does. Renewal that works but isn't picked up (a proxy that wasn't reloaded, a second certificate in a dual RSA/ECDSA setup, an HAProxy PEM that wasn't rebuilt) is the most common cause of expired certificates in production.

Small defaults that bite

Default Symptom Fix
Nginx client_max_body_size 1m uploads fail with 413 raise it per upload location
Nginx proxy_buffer_size 4k upstream sent too big header → 502 with large cookies/JWTs proxy_buffer_size 16k;
Nginx proxy_http_version 1.0 no upstream keep-alive, WebSockets fail proxy_http_version 1.1; + Connection header handling
proxy_pass https://… without proxy_ssl_verify on any backend certificate is accepted turn verification on (mTLS)
HAProxy without timeout client/server connections pile up forever always set all three timeouts

Test yourself

An upstream's DNS name now points to a new address, but Nginx keeps sending traffic to the old one. Why?

  1. DNS caching in the browser
  2. Hostnames in proxy_pass/upstream are resolved once at config load; use a resolver with a variable (or resolve in newer versions) to re-resolve
  3. Keepalive
  4. The TTL is too short

Behind a load balancer, which address in X-Forwarded-For is the real client?

  1. The leftmost
  2. The rightmost address that isn't one of your own trusted proxies
  3. The last one, always
  4. None of them

Why should inner timeouts be shorter than outer ones?

  1. To save memory
  2. So the inner layer fails first with a meaningful error, instead of continuing work for a client the outer layer already gave up on
  3. HTTP requires it
  4. It improves caching