Sub topic 14
Trade-offs and common pitfalls
A proxy gives you a place to centralize control, but every proxy is also an extra hop, an extra component to run, and an extra thing that can misreport what happened. This chapter assumes you know HTTP methods and headers, how TLS protects a connection, and the roles of forward and reverse proxies from earlier chapters. It covers what a proxy costs you and the mistakes that cause most proxy-related incidents.
What a proxy costs
Adding a proxy changes three things at once.
| Cost | Where it comes from | Typical mitigation |
|---|---|---|
| Latency | One more network hop, one more TCP (and possibly TLS) handshake, request and response buffering | Keep-alive connections to backends, place the proxy near the backends, cache |
| Availability risk | The proxy becomes a component every request must pass through | Run at least two proxies, health-check them, remove shared state |
| Lost information | The backend sees the proxy's address, not the client's | Forwarding headers plus a trusted-proxy rule |
| Operational load | More configuration, certificates, logs and metrics to manage | Configuration in version control, automated certificate renewal |
The latency is usually small, often one to a few milliseconds inside a data center. It grows quickly when the proxy opens a new connection to the backend for each request, or when it buffers large bodies to disk. A proxy that does useful work, such as serving cached responses or terminating TLS once for many requests, can lower total latency. A proxy that does nothing except forward traffic only adds to it.
Pitfall 1: the proxy as a single point of failure
If all traffic goes through one proxy, that proxy's failure takes down every backend behind it, however redundant the backends are. Adding a load balancer to make an application highly available moves the single point of failure up one layer unless you also make the proxy tier redundant.
Common ways this goes wrong:
- A single proxy VM fronts a pool of ten healthy backends.
- Two proxies exist, but DNS has only one address record, so clients never use the second.
- Both proxies share one resource, such as a disk-based cache volume, one certificate file, or one availability zone.
- Failover exists but has never been exercised, and it fails when needed.
Redundancy at the proxy tier needs an entry mechanism that can survive a proxy failure. Options include multiple DNS records, a floating IP moved by a health-checking protocol such as VRRP, or an anycast or cloud load balancer in front. Each option has its own failure time. DNS-based failover depends on client and resolver caching of TTLs, while floating IPs usually fail over in seconds.
Pitfall 2: losing or trusting the client IP
Behind a reverse proxy, the TCP peer address that the backend sees is the proxy's. Application logs, rate limiters, and geolocation then all treat every user as one address. The usual fix is to forward the original address in a header, but this introduces a second problem: the header is controlled by whoever sends the request.
The proxy configuration from earlier chapters uses $proxy_add_x_forwarded_for, which appends the connecting address to any existing X-Forwarded-For value. If a client sends a forged header, the backend receives both the forgery and the real address:
X-Forwarded-For: 1.2.3.4, 203.0.113.7Here 1.2.3.4 is a client-supplied lie and 203.0.113.7 is what the proxy actually observed. A backend that reads the leftmost entry trusts the forgery. A rate limiter keyed on that value can be bypassed by changing the header on each request, and an IP allow-list can be defeated.
The correct rule is to read the list from the right and skip addresses that belong to your own proxies. The first address that is not a trusted proxy is the client. In nginx, the realip module implements this rule:
# Trust forwarding headers only from our own proxy tier.
set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;
real_ip_recursive on;With these directives, $remote_addr becomes the first untrusted address from the right. Anything the client wrote to the left of it is ignored for that purpose.
The outermost proxy is a special case. Requests arrive there directly from the internet, so it should not trust any inbound X-Forwarded-For. It should overwrite the header with $remote_addr instead of appending to it:
proxy_set_header X-Forwarded-For $remote_addr;Use append ($proxy_add_x_forwarded_for) only on inner proxies that sit behind another trusted proxy.
Pitfall 3: backends that do not know the original scheme or host
TLS termination means the backend sees plain HTTP on a private port. If the backend generates absolute URLs or redirects from what it sees, it produces http:// links for users who connected over HTTPS. The usual symptoms are mixed-content warnings in the browser, a redirect loop (the backend redirects to HTTPS, the proxy forwards over HTTP, the backend redirects again), and cookies marked Secure that are never set.
The fix has two parts. The proxy sends X-Forwarded-Proto and the original Host, as in the earlier configuration. The application framework is then told to trust those headers from the proxy's address only. Many frameworks have a setting for this, such as trusted proxies or a proxy-headers option. Without it, the framework ignores the header and the problem remains.
The Host header has a related trap. By default nginx's proxy_pass sends the upstream name, here app_servers, as the Host header. A backend that uses virtual hosts, or that builds links from Host, will misbehave unless you set proxy_set_header Host $host;.
Pitfall 4: caching the wrong thing
A shared cache stores a response once and serves it to many users. The risks are leaking one user's data to another and serving stale or wrong content.
- Personalized responses cached as public. If
/accountreturns user-specific content and the proxy caches it by URL, the next user receives the first user's page. The default cache key in nginx is the scheme, host and URI, and it does not include cookies or authorization headers. - Missing
Varyhandling. If the backend returns different content depending on a request header, such asAccept-EncodingorAccept-Language, it must say so withVary. Otherwise the cache can return a compressed or localized variant to a client that cannot use it. - Stale content after a deployment. A ten-minute cache means a fix takes up to ten minutes to reach users, unless you purge or version the URLs (for example
app.3f9a1c.js). - Serving stale on errors hides outages.
proxy_cache_use_stale error timeout updating;improves availability, but it can also mask a backend that has been down for a long time. Monitor the cache status.
Restrict caching to paths you know are shared, as the earlier /static/ example does. Have backends send Cache-Control: private for per-user responses, and expose cache hits and misses in a response header so you can see what is happening:
location /static/ {
proxy_pass http://app_servers;
proxy_cache app_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_use_stale error timeout updating;
add_header X-Cache-Status $upstream_cache_status;
}Pitfall 5: timeouts, buffering, and mismatched limits
A request now crosses two connections, client to proxy and proxy to backend, each with its own timeouts and size limits. When they disagree, errors appear that neither side would produce alone.
- 502 Bad Gateway means the proxy received an invalid response or the connection failed. A common cause is a backend closing idle keep-alive connections sooner than the proxy expects, so the proxy sends a request on a connection that is already closed.
- 504 Gateway Timeout means the backend did not answer within the proxy's read timeout. The default in nginx is 60 seconds, which is too short for some report-generation endpoints and too long for most user-facing calls.
- 413 Request Entity Too Large appears when an upload exceeds the proxy's body limit (
client_max_body_size, 1 MB by default in nginx), even though the backend would accept it. - Streaming and long-lived responses break when the proxy buffers the whole response. For server-sent events or similar, disable buffering on that location with
proxy_buffering off;.
Make the limits explicit instead of relying on defaults:
location /api/ {
proxy_pass http://app_servers;
proxy_connect_timeout 2s;
proxy_read_timeout 30s;
proxy_http_version 1.1;
proxy_set_header Connection "";
client_max_body_size 10m;
}Setting proxy_http_version 1.1 and clearing the Connection header lets nginx keep connections to backends open, which removes a handshake from most requests.
A related trap is retries. If the proxy retries a failed request on another backend, a non-idempotent POST may run twice. By default, nginx does not retry non-idempotent methods after the request was sent, and you should keep it that way for any endpoint that creates records or charges money.
Pitfall 6: health checks that miss real failures
The max_fails and fail_timeout settings in the earlier load balancing example are passive health checks. The proxy learns a backend is bad only after real user requests fail, so a few users see errors every time a backend breaks. Passive checks also treat a slow backend as healthy as long as it eventually answers.
Active checks probe a dedicated endpoint on a schedule, so failures are found before users hit them. They have their own risk: a shallow check, such as "the process accepts connections", reports healthy while the database is unreachable. A deep check that queries every dependency can instead take every backend out of rotation at once when a shared dependency has a brief outage. Design the health endpoint to answer one question: can this instance serve requests right now?
Pitfall 7: forward proxy misconfiguration
Forward proxies have their own sharp edges.
- Open proxy. A forward proxy that accepts connections from any address will be found and used to relay abuse. The Squid configuration in this tutorial ends with
http_access deny alland permits only a named network, which is the safe pattern. Always end with an explicit deny. - CONNECT to arbitrary ports.
CONNECTopens a raw tunnel to any host and port the rule allows. Without restrictions, a client can tunnel to SSH or mail ports. RestrictCONNECTto port 443 unless you have a reason to allow others. - HTTPS is opaque by default. A forward proxy sees only the destination host and port in a
CONNECT, not the URLs or content. Path-level filtering requires TLS interception, which requires installing the proxy's certificate authority on every client and breaks applications that pin certificates. It also puts decrypted traffic in one place, which is an attractive target. - Clients bypassing the proxy. An explicit proxy works only if clients are configured to use it. Pair it with egress firewall rules that allow outbound traffic only from the proxy.
Choosing whether to add a proxy
Use a proxy when it replaces something you would otherwise duplicate in every service, such as TLS configuration, rate limiting, or access policy. Skip it, or delay it, when a single backend serves modest traffic and the extra hop provides nothing the backend cannot do.
When you do add one, check this list before going live:
- Run at least two proxy instances, with an entry point that survives losing one.
- Define which hops are trusted to set forwarding headers, and make the application read the client address accordingly.
- Pass
HostandX-Forwarded-Proto, and configure the application to trust them from the proxy only. - Cache only paths known to be shared, and make private responses uncacheable.
- Set connect, read and body-size limits explicitly.
- Use active health checks with a shallow, meaningful endpoint.
- End every forward proxy access list with a deny rule, and restrict
CONNECTports.
Exercise
Your backend rate-limits by client IP using the leftmost value of X-Forwarded-For. An attacker sends each request with a different forged X-Forwarded-For value and is never limited. The proxy uses proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; and is the only proxy, directly exposed to the internet. What is wrong, and what two changes fix it?
Show answer
The backend trusts a value the client controls. With $proxy_add_x_forwarded_for, the client's forged value stays at the left and the real address is appended on the right. Fix 1: because this proxy faces the internet directly, overwrite the header with proxy_set_header X-Forwarded-For $remote_addr; so no client-supplied value is passed on. Fix 2 (equivalent for the backend side): read the address from the right and skip trusted proxy addresses, for example with set_real_ip_from and real_ip_recursive on, instead of reading the leftmost entry.
Exercise
A site serves /dashboard through a caching reverse proxy with proxy_cache_valid 200 10m; applied to the whole site. Users report seeing other people's dashboards. Why does this happen, and how do you prevent it?
Show answer
The default cache key is built from the scheme, host and URI, not from cookies or authorization headers, so the first user's response for /dashboard is cached and served to everyone for ten minutes. Prevent it by caching only shared paths such as /static/ instead of the whole site, and by having the backend send Cache-Control: private (or no-store) on per-user responses so the proxy does not store them.