Skip to content

Forward vs Reverse Proxies ​

"A "gateway" (a.k.a. "reverse proxy") is an intermediary that acts as an origin server for the outbound connection but translates received requests and forwards them inbound to another server or servers." — RFC 9110, HTTP Semantics, section 3.7

Summary: A proxy is a program that sits in the middle of a connection and speaks for someone. A forward proxy speaks for the clients (it decides what they may reach and hides them from the origins); a reverse proxy speaks for the servers (it decides which server answers and hides the fleet from the clients). Almost every production request today crosses at least one reverse proxy, so the details (which header carries the client address, who may be believed, which timer produces a 504) are daily work, not theory. Focus: Forward proxies (egress control, caching, filtering, HTTP CONNECT tunnels, explicit vs transparent, PAC files, SOCKS5), reverse proxies (TLS termination vs passthrough, routing, caching, compression, rate limiting, WAF, header rewriting), L4 vs L7, X-Forwarded-For, Forwarded, X-Real-IP and the trusted-proxy problem, PROXY protocol, hop-by-hop headers, buffering, timeouts and the 502 vs 504 split, upstream keepalive, HTTP/2 vs HTTP/1.1 upstream, WebSocket proxying, health checks, graceful reload, sidecars and API gateways, with Go and Laravel 13 code and tests. Learning goal: Given a request path, name every proxy on it, say which of them terminates TLS, which header each one appends and which address each one is allowed to believe, state the timeout that fires first when the application is slow, and configure NGINX, HAProxy, Envoy, Go and Laravel so that the client address, scheme and host reach the application unforged.

This chapter sits in the Networking & Protocols group of system design. It owns the proxy as a design element. The mechanics around it live in siblings: Load Balancing owns the balancing algorithms, CDN owns edge caching as a product, Service Mesh & Sidecar owns the proxy-per-pod model, API Gateway, BFF & Service Mesh owns the gateway as an architecture decision, Rate Limiting Algorithms owns the algorithms behind a limiter, Timeouts, Retries & Jitter owns the retry math, and Cryptography, TLS, PKI & Secrets owns certificate design. The bytes under all of it are in TLS in Practice, Ports, Sockets & Connections and NAT, DHCP & Port Forwarding. Persian version: /fa/system-design/proxies-forward-reverse.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why proxies exist and the trade they makeWhy it exists
RFC 9110, SOCKS, X-Forwarded-For, PROXY protocol historyWhere it comes from
Egress control, filtering, caching, 407Forward proxy
HTTPS through a proxy, the tunnelHTTP CONNECT
Non-HTTP traffic through a proxySOCKS5
Configured vs intercepted proxies, PAC filesExplicit, transparent and PAC
What a reverse proxy does for a server fleetReverse proxy
Byte relay vs HTTP-aware proxyL4 vs L7
Who holds the certificateTLS termination, passthrough, re-encryption
X-Forwarded-For, Forwarded, X-Real-IPForwarding headers
Forged client IPs, Laravel TrustProxiesThe trusted-proxy problem
Client address at L4PROXY protocol
Connection, Upgrade, ViaHop-by-hop headers
Slow clients, big bodies, streamingBuffering
502 vs 504 and every timerTimeouts
HTTP/2 front, HTTP/1.1 back, connection poolsConnection reuse
Chat, SSE, long-lived connectionsWebSocket proxying
Ejecting dead servers, safe retriesHealth checks
Deploying config without dropping requestsGraceful reload
Caching, compression, rate limiting, WAF at the proxyWhat else a reverse proxy does
Sidecar and API gatewaySidecar and gateway
NGINX, HAProxy, Envoy, Traefik, Caddy, Squid, Cloudflare, ALBProducts
Knobs, status codes, log linesMechanics
CodeGo, Laravel
Classic production failuresSolving the classic problems
Which proxy for which jobChoosing
Monolith to distributed systemIn architecture
A lab you can run in a terminalLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Forward vs reverse. Same mechanism, opposite owner.

Forward proxy (egress proxy)Reverse proxy (gateway)
Who configures itThe client side: browser, OS, PAC file, environment variable, or a network deviceThe server side: whoever owns the domain
How traffic reaches itThe client is told about it (explicit) or is silently steered to it (transparent)DNS points the public name at it
Whom it hidesThe clients from the originsThe origins from the clients
Typical jobsEgress allow-list, content filtering, shared cache, audit log, anonymityTLS termination, routing, load balancing, caching, compression, rate limiting, WAF
Request formAbsolute-form GET http://host/path or CONNECT host:443Normal origin-form GET /path with a Host header
Typical productsSquid, corporate secure web gateways, tinyproxyNGINX, HAProxy, Envoy, Traefik, Caddy, Cloudflare, AWS ALB

Layer 4 vs layer 7. The layer decides what the proxy can see and therefore what it can do.

L4 proxy (TCP/UDP)L7 proxy (HTTP)
SeesIP addresses, ports, bytes, sometimes the TLS SNI nameMethod, path, headers, cookies, body
Can doBalance connections, TLS passthrough, fail overRoute by path or host, rewrite headers, cache, limit per user, retry a request
Cannot doRoute by URL, add X-Forwarded-For, cacheHandle protocols it does not parse
CostCheap, very fast, protocol-agnosticCPU for parsing and TLS; it is a full HTTP implementation you must trust
ExamplesHAProxy mode tcp, AWS NLB, NGINX streamNGINX http, HAProxy mode http, Envoy HTTP connection manager, AWS ALB

The client address problem. After one proxy, the TCP peer is the proxy. The original address survives only if the proxy writes it down and the next hop believes only proxies it knows.

MechanismLayerWritten byBelieve it when
X-Forwarded-ForHTTPEvery proxy appends the peer it sawThe TCP peer is a proxy you operate; read from the right
Forwarded (RFC 7239)HTTPProxies that support the standard formSame rule; parse for=, proto=, host=, by=
X-Real-IPHTTPOne proxy, usually the outermost you ownThe proxy overwrote it, never copied the client value
PROXY protocol v1/v2TCPThe L4 proxy, once at the start of the connectionThe listener accepts it only from known proxies
CF-Connecting-IP (Cloudflare)HTTPCloudflare edgeOnly when the request really came from Cloudflare ranges

Who answers when it fails.

SymptomStatusWho produced itFirst thing to check
Upstream refused or reset the connection502 Bad GatewayThe proxyIs the app listening, was it restarting, did the port change
Upstream sent garbage or closed mid-response502 Bad GatewayThe proxyApp crash, header too large, protocol mismatch (HTTP to a TLS port)
Upstream did not answer in time504 Gateway TimeoutThe proxyThe proxy read timeout versus the real work time
No healthy upstream left502 or 503 (product dependent)The proxyHealth check, deploy in progress, ejection
Client sent the body too slowly408 Request TimeoutThe proxyMobile clients, body timeout
Body bigger than allowed413 Content Too LargeThe proxyclient_max_body_size in NGINX

Why it exists ​

A direct connection from a client to a server gives both sides full information and full exposure: the server learns the client address and sees every byte of the client's behaviour; the client can reach any server it can route to. That is simple, and it breaks four things at scale.

  1. Control. An organisation wants to say which sites its machines may reach, and log it. A server fleet wants to say which public requests reach which service. Neither can be done well inside every application.
  2. Shared work. TLS, compression, caching, rate limiting, authentication of the edge and request logging are the same for every service. Doing them once in a proxy is cheaper than doing them in every codebase.
  3. Decoupling. Clients should not know how many servers exist, which one is being deployed, or which port the app uses. A proxy gives the public name a stable face.
  4. Protection. The application server is slow, stateful and full of business logic. A proxy absorbs slow clients, bad requests and floods before they occupy a worker.

The price: one more hop (about 0.1 to 1 ms inside a data centre), one more thing to fail, one more place where the truth about the client is rewritten, and one more set of timers that can disagree with yours.

Simple direct connectionProxy in the middle
Server sees the real peer addressServer sees the proxy; the real address travels in a header you must trust carefully
One TLS handshake, end to endTLS may end at the proxy; the hop behind it may be plain or re-encrypted
One timeout storyA timer per hop; the smallest wins and produces a different status code
Nothing to deployA fleet, config, certificates, reloads and monitoring of its own
Clients know the serverClients know the name; the proxy knows the servers

An everyday picture. A reverse proxy is the reception desk of an office building: visitors only know the street address, reception checks who they are, sends them to the right floor, turns away trouble, and tells the person upstairs "a visitor from the courier company is on the way". A forward proxy is the company mail room for outgoing post: staff hand it letters, it checks they may be sent, stamps them with the company return address, and keeps a log. The visitor's name written on a note by reception is useful only if the person upstairs knows the note really came from reception and not from a visitor who wrote it himself. That note is X-Forwarded-For.

Forward proxy: the client chooses itReverse proxy: the server owner runs itClients(browsers, jobs)Forward proxypolicy, cache, logInternetmany originsCONNECT / GETClients(internet)Reverse proxyTLS, route, limitapp-1 :8080app-2 :8080api :9000knows the client; hides or controls egressknows the origins; hides them from clientsSet in the client: PAC file, proxy env vars, browser settingor intercepted (transparent). Examples: Squid, gatewaysChosen by DNS: the public name points at the proxy.NGINX, HAProxy, Envoy, Traefik, Caddy, Cloudflare, AWS ALB

Three common misunderstandings, up front ​

  1. "A proxy is a security product." A proxy is a place where security controls can live; by itself it also adds a new component that can leak, mis-route and spoof.
  2. "X-Forwarded-For tells you the client IP." It tells you what the last untrusted party wrote, followed by what each proxy appended. Only the entries added by your own proxies are facts.
  3. "A 504 means the application is slow, a 502 means it is down." A 504 means the proxy's timer fired; the application may still be working (and will finish the work after the client has left). A 502 means the proxy could not get a valid response, including after a crash mid-response.

Where it comes from ​

The word "proxy" in HTTP is defined, in the current specification, as "a message-forwarding agent that is chosen by the client, usually via local configuration rules, to receive requests for some type(s) of absolute URI" (RFC 9110, section 3.7). The same section defines the gateway ("a.k.a. reverse proxy") and the tunnel ("a blind relay between two connections without changing the messages"). Those three words are the whole vocabulary of this chapter.

DateMilestoneSource
1996SOCKS Protocol Version 5 (RFC 1928) generalises a firewall-traversal framework to any application protocol; it adds authentication negotiation and UDPRFC 1928
Long establishedCaching forward proxies such as Squid ("a high-performance proxy caching server for web clients") are an established product categorySquid FAQ (undated)
Before 2014X-Forwarded-For, X-Forwarded-By and X-Forwarded-Proto exist as "non-standard header fields" used by common load balancersRFC 7239, section 1
2014RFC 7239 standardises the Forwarded header field with for, by, host and proto parametersRFC 7239
2012 to 2020HAProxy's PROXY protocol (v1 text, v2 binary) lets "dumb" TCP proxies pass the original connection parametersHAProxy proxy-protocol spec
2022RFC 9110 consolidates HTTP semantics: proxy, gateway, tunnel, CONNECT, Via, hop-by-hop handling in the Connection fieldRFC 9110
TodayEnvoy ("an L7 proxy and communication bus") runs beside every service as an out-of-process proxyEnvoy docs

The PROXY protocol row spans the revision dates in the specification's own changelog (the first entries are from 2012, the latest from 2020). The Squid row carries no date because the page read does not give one.

The concept catalogue ​

Forward proxy and egress control Must-know ​

In plain words: A forward proxy is a server you route your outgoing traffic through. Instead of each laptop or server connecting straight to the internet, they ask the proxy to connect for them, and the proxy can say yes, no, or "from cache".

Common misunderstanding: "A forward proxy is for hiding your IP." Anonymity is one use. In companies the main uses are the opposite: control (an egress allow-list), accountability (every request logged with who sent it), and saving bandwidth with a shared cache. A server that may call only three external APIs and nothing else is a forward proxy use case, and it is the one that stops data exfiltration and SSRF from becoming incidents.

Definition: An intermediary chosen by the client that receives requests for absolute URIs (GET http://example.org/a HTTP/1.1) or tunnel requests (CONNECT example.org:443) and forwards them to the origin, applying policy on the way. The policy points are: who may use it (authentication, 407), where they may go (allow or deny by domain, category or IP), what happens to the response (cache, scan, rewrite) and what is recorded.

 1  app        -> proxy   CONNECT api.payments.example:443 HTTP/1.1   Proxy-Authorization: Basic ...
 2  proxy                 policy: service "billing" may reach *.payments.example:443 -> allow
 3  proxy      -> origin  TCP connect to api.payments.example:443
 4  proxy      -> app     HTTP/1.1 200 Connection Established
 5  app        <-> origin TLS handshake and HTTPS, relayed blindly by the proxy
 6  proxy                 log: billing -> api.payments.example:443, 12.4 KB up, 88 KB down, 340 ms

Real scenario: A bank allows application servers to reach only a payment provider and a time server; everything else is dropped at the firewall and permitted solely through Squid with an allow-list. A research lab caches OS package downloads in Squid so a hundred machines pull the same file once. A SaaS runs customer-supplied webhook URLs through a hardened egress proxy that refuses private address ranges, which is the standard SSRF defence for outbound fetches. A school filters categories of sites.

ProductRole as forward proxyNotes
SquidCaching and filtering forward proxy; ACLs in squid.conf (`http_access allowdeny`)
NGINXCan forward plain HTTP with resolver and proxy_pass $http_host$request_uri, but has no native CONNECT supportUse a CONNECT module or a purpose-built forward proxy for HTTPS
HAProxyMostly reverse; can be a plain forward relay with ACLsNot designed as a filtering forward proxy
EnvoyDynamic forward proxy filter for in-mesh egressEgress gateway pattern in service meshes
Cloud NAT / firewall appliancesL3/L4 egress, no HTTP awarenessCombine with a proxy when you need domain-level policy

Fix / how to use it: the code in Go shows a forward proxy with a destination allow-list and proxy authentication. On the Laravel side, application egress is pointed at the proxy with Guzzle's proxy option passed through Http::withOptions (see Laravel). Never try to enforce an egress allow-list only in the application: it must be enforced where a compromised application cannot switch it off, the network and the proxy.

sql
-- Egress audit table fed by the proxy log (PostgreSQL)
CREATE TABLE egress_log (
  id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  logged_at     timestamptz NOT NULL DEFAULT now(),
  source_ip     inet        NOT NULL,
  principal     text        NOT NULL,          -- authenticated proxy user or service name
  method        text        NOT NULL,          -- GET, CONNECT ...
  destination   text        NOT NULL,          -- host:port
  decision      text        NOT NULL CHECK (decision IN ('allow','deny')),
  bytes_up      bigint      NOT NULL DEFAULT 0,
  bytes_down    bigint      NOT NULL DEFAULT 0
);
CREATE INDEX egress_log_dest_idx ON egress_log (destination, logged_at DESC);

-- Which services talk to destinations nobody approved?
SELECT principal, destination, count(*) AS denied
FROM egress_log
WHERE decision = 'deny' AND logged_at > now() - interval '1 day'
GROUP BY principal, destination
ORDER BY denied DESC
LIMIT 20;

HTTP CONNECT and tunnels Must-know ​

In plain words: HTTPS is encrypted from your machine to the website, so a proxy cannot read it. CONNECT is the request "please open a TCP pipe to that host and port and then just pass bytes". After the proxy says 200, it stops being an HTTP participant and becomes a pipe.

Common misunderstanding: "A forward proxy can see my HTTPS URLs." With CONNECT it sees only the destination host and port (and, if it also looks at the handshake, the SNI name), the amount of data and the timing. It cannot see the path, headers or body unless it performs TLS interception: it presents its own certificate, your device trusts the company root CA, and the proxy opens a second TLS session to the origin. That is a deliberate man-in-the-middle and must be disclosed and managed as such.

Definition: RFC 9110, section 9.3.6: "The CONNECT method requests that the recipient establish a tunnel to the destination origin server identified by the request target and, if successful, thereafter restrict its behavior to blind forwarding of data, in both directions, until the tunnel is closed." The request target is in authority-form (host:port), not a path.

 1  client -> proxy    CONNECT shop.example:443 HTTP/1.1
                       Host: shop.example:443
                       Proxy-Authorization: Basic c3ZjOnMzY3JldA==
 2  proxy  -> origin   TCP SYN to shop.example:443
 3  proxy  -> client   HTTP/1.1 200 Connection Established
 4  client -> origin   TLS ClientHello (SNI: shop.example), relayed
 5  origin -> client   ServerHello, certificate, Finished, relayed
 6  client <-> origin  encrypted application data; proxy copies bytes both ways
 7  either side closes -> proxy closes the other half (half-close is propagated)

Real scenario: HTTPS_PROXY=http://proxy.corp.example:3128 curl https://api.example.org issues the exchange above. A CI runner behind a corporate proxy needs HTTPS_PROXY and NO_PROXY set, otherwise npm install hangs. A proxy that answers 403 to CONNECT for a destination on a block list is the normal "blocked by policy" experience. Some proxies allow CONNECT only to port 443; allowing it to arbitrary ports turns the proxy into a generic TCP relay, which attackers use to reach internal services (the proxy-as-pivot problem).

ProductCONNECT behaviour
SquidSupported; restricted by acl SSL_ports port 443 and http_access deny CONNECT !SSL_ports in the default config
NGINXhttp module does not implement CONNECT; use the stream module or a different proxy
HAProxyCan accept CONNECT in mode http with ACLs on the authority
EnvoyCONNECT supported with upgrade_configs: CONNECT and tunnelling (used for HTTP/2 and HTTP/3 proxying)
Go net/http clientHonors HTTPS_PROXY through http.ProxyFromEnvironment and issues CONNECT automatically

Fix / how to use it: the Go forward proxy in Go implements the connect method: check policy on the authority, dial with a timeout, hijack the client connection, reply 200 Connection Established, copy both directions, and propagate half-close with CloseWrite. The test TestConnectTunnelsBytes proves bytes go both ways; TestConnectDeniedByPolicy proves a 403.

SOCKS5 Good to know ​

In plain words: SOCKS5 is a proxy protocol below HTTP. The client says "connect me to this address and port" in a small binary message, and the proxy relays any protocol: SSH, SMTP, a database, a game.

Common misunderstanding: "SOCKS is just a faster HTTP proxy." SOCKS does not understand HTTP at all, so it cannot cache, filter by URL or add headers. Its strength is generality, which is also the reason security teams treat it with suspicion.

Definition: RFC 1928 defines three steps. The client sends a version identifier and a list of authentication methods (X'00' no authentication, X'02' username/password, X'FF' none acceptable from the server); the server picks one; the client then sends a request with CMD (CONNECT, BIND or UDP ASSOCIATE), an address type (IPv4, domain name or IPv6), the destination address and port; the server replies with a status and the bound address.

 1  client -> proxy   05 02 00 02                     version 5, two methods: none, user/pass
 2  proxy  -> client  05 02                           chosen method: username/password
 3  client -> proxy   01 04 'svc' 06 's3cret'         RFC 1929 sub-negotiation
 4  proxy  -> client  01 00                           authentication ok
 5  client -> proxy   05 01 00 03 0B 'example.org' 01 BB   CONNECT, domain name, port 443
 6  proxy  -> client  05 00 00 01 <bound addr/port>   succeeded
 7  client <-> origin raw bytes relayed (any protocol)

Real scenario: ssh -o ProxyCommand through a SOCKS proxy; curl --socks5-hostname proxy:1080 (hostname resolved by the proxy, which avoids DNS leaks); ssh -D 1080 bastion creating a local SOCKS5 proxy over an SSH tunnel; Tor exposes a SOCKS5 port. In Kubernetes, SOCKS is rare; HTTP CONNECT or mesh egress is used instead.

QuestionHTTP proxy with CONNECTSOCKS5
Understands HTTPYes for plain requests, no after CONNECTNo
Non-HTTP protocolsOnly via CONNECT on allowed portsNative
UDPNoUDP ASSOCIATE
DNS resolution at the proxyYes, authority carries the host nameYes with the domain-name address type (socks5h in curl)
AuthenticationProxy-Authorization (407)Method negotiation (RFC 1929 username/password)
Policy granularityDomain, URL (plain), methodDestination address and port only

Fix / how to use it: prefer HTTP CONNECT where the client supports it, because Squid-style ACLs are richer. Use SOCKS5 when the protocol is not HTTP. In Go, golang.org/x/net/proxy provides a SOCKS5 dialer; in Laravel, SOCKS is not covered by the Laravel or Guzzle pages read for this chapter, so check the cURL handler documentation before relying on it.

Explicit proxy, transparent proxy and PAC files Important ​

In plain words: An explicit proxy is one the client knows about and is configured to use. A transparent (intercepting) proxy is one the network quietly steers traffic into, so the client never knows.

Common misunderstanding: "Transparent means invisible to security tools." Transparent only means the client needs no configuration. HTTPS interception needs a trusted CA on the client, and anything the proxy cannot decrypt (certificate pinning, mTLS) breaks. Explicit proxies fail loudly (the client reports proxy errors); transparent ones fail strangely (connection resets, certificate warnings).

Definition: Explicit proxy: the client sends absolute-form requests or CONNECT to the proxy's address. Transparent proxy: the router or firewall redirects TCP port 80 and 443 to the proxy (iptables REDIRECT/TPROXY, a WCCP router, or a cloud firewall); the proxy recovers the destination from the original destination socket option or from the Host header and SNI. A PAC (proxy auto-config) file is a JavaScript function FindProxyForURL(url, host) that the browser downloads and runs for each URL; it returns DIRECT, PROXY host:port, SOCKS5 host:port or a semicolon separated fallback list.

 1  browser -> wpad/PAC server   GET http://wpad.corp.example/proxy.pac
 2  browser                       runs FindProxyForURL("https://api.corp.example/x", "api.corp.example")
 3  browser                       result "DIRECT": connects straight to the internal API
 4  browser                       runs FindProxyForURL("https://news.example.org/", "news.example.org")
 5  browser                       result "PROXY proxy1.example:3128; PROXY proxy2.example:3128"
 6  browser -> proxy1            CONNECT news.example.org:443 (proxy2 only if proxy1 is unreachable)

Real scenario: A laptop fleet gets its PAC URL from MDM; internal names go DIRECT and everything else goes to the proxy pool. A Kubernetes cluster uses a transparent egress gateway (an Envoy or Squid pod) with iptables redirection from the node so that workloads need no HTTP_PROXY variables. A developer sees ERR_TUNNEL_CONNECTION_FAILED in Chrome: the PAC file returned a proxy that rejected CONNECT.

AspectExplicitTransparent
Client configNeeded (proxy settings, PAC, env vars)None
Failure visibilityClear proxy error pages and 407/403Resets, timeouts, certificate warnings
HTTPSCONNECT; host and port visible, content opaque unless interceptedNeeds interception with a trusted CA, or only SNI-based decisions
Authentication407 Proxy-Authentication RequiredHard: usually by source IP or device certificate
Typical placeUser laptops, CI runnersBranch networks, egress gateways, guest Wi-Fi

Fix / how to use it: see the sample PAC below. Keep PAC logic short (it runs for every URL in the browser), return DIRECT for internal names and ranges first, never return DIRECT as a fallback if policy requires the proxy.

pac
// Proxy auto-config (PAC): a JavaScript function the browser calls per URL.
function FindProxyForURL(url, host) {
  if (isPlainHostName(host) || dnsDomainIs(host, ".internal.example")) {
    return "DIRECT";                                     // never proxy internal names
  }
  if (isInNet(host, "10.0.0.0", "255.0.0.0")) {
    return "DIRECT";
  }
  // Primary proxy, then a standby, then give up (do not fall back to DIRECT: that would bypass policy).
  return "PROXY proxy1.example:3128; PROXY proxy2.example:3128";
}

Reverse proxy Must-know ​

In plain words: A reverse proxy is the front door of your servers. Clients connect to it thinking it is the website; it passes each request to a real server behind it and passes the answer back.

Common misunderstanding: "A reverse proxy is just a load balancer." Load balancing is one of at least a dozen jobs: TLS termination, routing by host or path, caching, compression, rate limiting, request size limits, authentication offload, header normalisation, WAF rules, access logs, redirects, canary traffic splitting and graceful draining during deploys. A load balancer that understands HTTP is a reverse proxy; a reverse proxy with one backend is still useful.

Definition: An HTTP gateway: it accepts the client connection as if it were the origin, then opens its own connection to an upstream server (an origin or an application server), forwards a possibly rewritten request, and relays the response. The two connections are independent: different TLS sessions, different HTTP versions, different keepalive state, different timeouts. The set of backends is the upstream (NGINX term; HAProxy calls it a backend, Envoy a cluster, Traefik a service, Caddy an upstream).

 1  client   -> proxy     TLS handshake, HTTP/2 GET /orders/42  Host: shop.example
 2  proxy                 terminate TLS, parse request, check rate limit and WAF rules
 3  proxy                 route: Host shop.example, path /orders -> pool "orders" (2 healthy of 3)
 4  proxy    -> orders-2  GET /orders/42 HTTP/1.1  X-Forwarded-For: 198.51.100.7  X-Forwarded-Proto: https
 5  orders-2 -> proxy     200 OK, 12 KB
 6  proxy                 add Via, strip internal headers, compress if allowed, write access log
 7  proxy    -> client    HTTP/2 200 OK

Real scenario: NGINX in front of PHP-FPM or Laravel Octane; HAProxy balancing a database pool in mode tcp; Envoy as the ingress of a Kubernetes cluster; Cloudflare in front of the whole site (a reverse proxy run by a third party); an AWS Application Load Balancer routing /api/* to one target group and / to another.

JobNGINXHAProxyEnvoyTraefikCaddy
Basic proxyingproxy_passbackend + servercluster + routerouter + servicereverse_proxy
Active health checksPlus only (health_check)check on serverhealth_checks on clusterhealthCheck on servicehealth_uri
Passive ejectionmax_fails, fail_timeoutobserve, on-erroroutlier detectionnot nativefail_duration, max_fails
Dynamic configreload; Plus APIruntime API, reloadxDS APIsproviders (Docker, K8s)API, reload
Typical roleEdge, app tierEdge, L4 and L7 balancerMesh sidecar and gatewayContainer ingressSimple edge with automatic HTTPS

Fix / how to use it: the working reference config is below (NGINX). It shows upstream keepalive, HTTP/1.1 to the upstream, forwarding headers, tight timeouts, retries, a WebSocket location and buffering choices; each of these is explained in its own block.

conf
# NGINX reverse proxy in front of an application tier (L7).
# Reload without dropping connections: nginx -t && nginx -s reload
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

upstream app {
    zone app 64k;                     # shared memory so all workers see the same state
    server 10.0.1.11:8080 max_fails=2 fail_timeout=10s;
    server 10.0.1.12:8080 max_fails=2 fail_timeout=10s;
    keepalive 32;                     # idle upstream connections kept per worker
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;                         # HTTP/2 to the client ...
    server_name app.example.com;
    ssl_certificate     /etc/nginx/tls/app.example.com.pem;
    ssl_certificate_key /etc/nginx/tls/app.example.com.key;

    # Believe the PROXY protocol or X-Forwarded-For only from our own L4 load balancer.
    set_real_ip_from 10.0.0.0/8;
    real_ip_header   X-Forwarded-For;
    real_ip_recursive on;

    client_max_body_size 10m;

    location / {
        proxy_pass http://app;
        proxy_http_version 1.1;       # ... HTTP/1.1 upstream, needed for keepalive upstream
        proxy_set_header Connection "";                    # clear the hop-by-hop header so the connection stays open
        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_connect_timeout 3s;     # default 60s is far too long for a user-facing path
        proxy_send_timeout    30s;
        proxy_read_timeout    30s;    # gap between two reads, not the whole response
        proxy_next_upstream error timeout http_502 http_503;
        proxy_next_upstream_tries 2;  # idempotent requests only (default behaviour)

        proxy_request_buffering on;   # whole request body is read before the upstream sees it
        proxy_buffering on;           # slow clients do not tie up the app tier
    }

    location /ws/ {
        proxy_pass http://app;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_read_timeout 1h;        # an idle WebSocket is silent; give it room
        proxy_buffering off;
    }
}

Layer 4 and layer 7 proxies Must-know ​

In plain words: A layer 4 proxy moves bytes between two TCP connections without reading them. A layer 7 proxy reads the HTTP messages, so it can make decisions about each request.

Common misunderstanding: "L7 is always better because it knows more." L7 pays for knowledge: it must parse every message, hold buffers, and agree with the client on every HTTP detail, so it has a larger attack surface and more CPU cost. L4 is the right choice for non-HTTP protocols (databases, MQTT, SMTP), for TLS passthrough, for extreme throughput, and as the first tier that spreads connections across several L7 proxies.

Definition: L4 (transport) proxy: decisions based on the 5-tuple and, optionally, the TLS SNI name; one client connection maps to one upstream connection. L7 (application) proxy: decisions based on parsed protocol messages; one client connection can be multiplexed over many upstream connections (and the reverse).

L4 proxy: bytes in, bytes outL7 proxy: parse, decide, rewriteClientL4 proxyTCP + PROXY hdrServerterminates TLSsees: IPs, ports, SNI, bytescannot: route by path, add headersClientL7 proxyterminates TLSapp-1 (plain HTTP)app-2 (plain HTTP)/api -> api poolsees: method, path, headers, cookies; can cache, limit, rewritecost: CPU for TLS + parsing, a full HTTP implementation to trustPassthrough keeps TLS end to end (L4). Termination decrypts at the proxy (L7). Re-encryption adds TLS upstream.
 1  client -> L4 proxy   SYN
 2  L4 proxy             pick backend by round robin or least connections (no HTTP parsed)
 3  L4 proxy -> backend  SYN; then PROXY protocol header: PROXY TCP4 198.51.100.7 203.0.113.10 52341 443
 4  client <-> backend   TLS and HTTP flow through untouched
 5  L7 proxy -> backend  (alternative) parsed request, pooled connection, X-Forwarded-For added

Real scenario: AWS Network Load Balancer in front of an NGINX fleet (L4 tier spreading connections, L7 tier doing HTTP); HAProxy mode tcp in front of PostgreSQL replicas; NGINX stream for MySQL or syslog; AWS ALB routing by path; Envoy as an L3/L4 proxy with HTTP filters on top ("At its core, Envoy is an L3/L4 network proxy" with an HTTP filter on top, per its docs).

CapabilityL4 proxyL7 proxy
Route by host or pathNo (SNI only)Yes
Preserve end-to-end TLSYes (passthrough)No unless re-encrypted
Add or rewrite headersNoYes
Per-request retry and metricsNo (per connection)Yes
Websocket and gRPC awarenessOpaque bytesUnderstands Upgrade and HTTP/2 streams
Typical throughput costLowestHigher CPU per request

Fix / how to use it: use an L4 tier when you need passthrough or non-HTTP protocols, and let it hand the client address to the L7 tier with the PROXY protocol. Put per-request logic in the L7 tier.

TLS termination, passthrough and re-encryption Must-know ​

In plain words: Someone must hold the private key and do the encryption maths. Termination means the proxy does it and talks plain HTTP behind it. Passthrough means the proxy does not touch TLS and the backend does it. Re-encryption means the proxy decrypts, inspects, then opens a new TLS connection to the backend.

Common misunderstanding: "If the proxy terminates TLS my traffic is unencrypted." Only the segment behind the proxy is plain, and only if you configure it so. In a trusted private network that may be acceptable; in a shared network, cloud multi-tenant VPC or zero-trust model you re-encrypt (and often use mTLS between proxy and upstream, see mTLS service security).

Definition: Termination (offload): the proxy completes the handshake with the client using the public certificate; upstream is HTTP or HTTPS (re-encryption) with its own trust. Passthrough: the L4 proxy relays the encrypted stream, choosing the backend with the SNI value in the ClientHello when needed. The certificate then lives on the backend.

ModelWho has the certificateProxy can see the requestCost and risk
Termination, plain upstreamProxyYesCheapest; the hop behind the proxy is cleartext
Termination + re-encryptionProxy (public) and backend (private CA)YesTwo handshakes; certificate management twice
Termination + mTLS upstreamProxy and backend, both verifyYesStrong internal identity; more certificates
PassthroughBackendNo (SNI and bytes only)No L7 features at the proxy; client address needs PROXY protocol
 1  client -> proxy     ClientHello (SNI shop.example, ALPN h2, http/1.1)
 2  proxy               holds shop.example certificate -> terminate: ServerHello with its certificate
 3  client <-> proxy    HTTP/2 over TLS 1.3
 4  proxy -> app        HTTP/1.1 over plain TCP, X-Forwarded-Proto: https
 5  app                 builds absolute URLs; must trust X-Forwarded-Proto or it will emit http:// links

Real scenario: Cloudflare terminates TLS at its edge and connects to the origin in "Flexible" (plain) or "Full" modes; an ALB with an ACM certificate terminates TLS and speaks HTTP to targets; an NLB with TCP listeners does passthrough; a bank requires re-encryption inside the data centre. The classic bug: the app generates http:// links or redirect loops behind a terminating proxy because it believes the connection was plain; the fix is a trusted X-Forwarded-Proto (see Laravel).

Fix / how to use it: terminate at an L7 proxy for routing and WAF; pass through when the backend must own the key (regulated keys, client certificates validated by the app); re-encrypt in multi-tenant networks. Certificate lifecycle and PKI: Cryptography, TLS, PKI & Secrets. Handshake bytes: TLS in Practice.

Forwarding headers: X-Forwarded-For, Forwarded, X-Real-IP Must-know ​

In plain words: When a proxy forwards a request, the server sees the proxy as the sender. So the proxy adds a note: "the connection really came from this address, using this scheme, for this host".

Common misunderstanding: "X-Forwarded-For is a standard that carries one IP." It is a de facto convention, a comma-separated list; RFC 7239 calls these "non-standard header fields". Each proxy appends the address of the peer that connected to it. A client may also send its own X-Forwarded-For, which the first proxy happily keeps unless told otherwise.

Definition: X-Forwarded-For: client, proxy1, proxy2 (the last proxy's own address is not in the list; it is the TCP peer of the application). X-Forwarded-Proto carries the scheme the client used, X-Forwarded-Host the original Host, X-Forwarded-Port the original port. X-Real-IP is a single value set by one proxy (NGINX: proxy_set_header X-Real-IP $remote_addr). The standard Forwarded field (RFC 7239) combines them in one header: Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43, with IPv6 and unknown identifiers quoted: for="[2001:db8:cafe::17]:4711".

 1  attacker -> CDN        GET /  X-Forwarded-For: 203.0.113.99
 2  CDN      -> balancer   X-Forwarded-For: 203.0.113.99, 198.51.100.7           (CDN appends the peer it saw)
 3  balancer -> nginx      X-Forwarded-For: 203.0.113.99, 198.51.100.7, 10.0.0.4 (balancer appends the CDN address)
 4  nginx    -> app        X-Forwarded-For: 203.0.113.99, 198.51.100.7, 10.0.0.4, 10.0.0.9
 5  app                    TCP peer is 10.0.0.12; the first entry is a lie, the real client is 198.51.100.7
X-Forwarded-For grows by one entry per trusted hop; trust ends at the first unknown addressAttackersends forged XFFCDN edge(trusted)L4/L7 balancer(trusted)App proxyNGINX (trusted)Applicationreads client IPpeer 198.51.100.7peer 203.0.113.50peer 10.0.0.4peer 10.0.0.9XFF at the app: 203.0.113.99 (forged), 198.51.100.7, 10.0.0.4Walk from the right: 10.0.0.4 is ours, skip; 198.51.100.7 is not ours, stop. Client = 198.51.100.7The leftmost entry is attacker-controlled; never use it for rate limits or allow-lists

Real scenario: A login rate limiter keyed by the first X-Forwarded-For value is bypassed with a new random header per request. An audit log shows every user coming from the load balancer's private address because the app reads REMOTE_ADDR. An allow-list for an admin panel is bypassed by sending X-Forwarded-For: 10.0.0.1 through a proxy that appends rather than replaces. AWS ALB has an attribute routing.http.xff_header_processing.mode with append (the default), preserve and remove; Cloudflare sends CF-Connecting-IP with the client address; Envoy decides the trusted client address with use_remote_address and xff_num_trusted_hops.

HeaderStandardFormatWho writes itNotes
X-Forwarded-ForDe factoComma-separated addressesEach proxy appendsRead right to left through trusted hops
X-Forwarded-ProtoDe factohttp or httpsThe terminating proxyNeeded for correct redirects and absolute URLs
X-Forwarded-HostDe factoOriginal HostProxy that rewrote HostOnly trusted from known proxies; Host header attacks
X-Forwarded-PortDe factoPort numberProxyAbsolute URLs with non-default ports
ForwardedRFC 7239for=, by=, host=, proto=Proxies that implement itAdoption is partial; many stacks still use X-Forwarded-*
X-Real-IPConvention (NGINX)Single addressOne chosen proxyMust be overwritten, not passed through
CF-Connecting-IPCloudflareSingle addressCloudflare edgeTrust only if the request came from Cloudflare
ViaRFC 91101.1 pseudonymEvery proxyDiagnostics and loop detection, not identity

Fix / how to use it: one rule: the outermost proxy you own must discard (or overwrite) any forwarding header it receives from an untrusted peer, and every inner hop trusts only the peers in a list. The Go package clientip implements the right-to-left walk and rproxy overwrites X-Real-IP and rebuilds X-Forwarded-For from a trusted-peer decision.

go
// Package before is the naive way to find the client address behind a proxy.
// It is bad design on purpose: it trusts a header that any client can send.
package before

import (
	"net/http"
	"strings"
)

// ClientIP returns the first entry of X-Forwarded-For when present.
// The first entry is whatever the original caller wrote, so an attacker
// controls it: "X-Forwarded-For: 203.0.113.99" makes any rate limiter,
// allow-list or audit log believe the request came from 203.0.113.99.
func ClientIP(r *http.Request) string {
	if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
		return strings.TrimSpace(strings.Split(xff, ",")[0])
	}
	return r.RemoteAddr
}
go
// Package clientip finds the real client address behind a chain of proxies.
//
// Rule: only believe a forwarding header when the TCP peer that delivered the
// request is a proxy you operate. Then walk X-Forwarded-For from the right
// (the entry your own proxy appended) toward the left and stop at the first
// address that is not one of your proxies.
package clientip

import (
	"net"
	"net/netip"
	"strings"
)

// Parse turns a comma separated list of prefixes or addresses into prefixes.
func Parse(cidrs ...string) ([]netip.Prefix, error) {
	out := make([]netip.Prefix, 0, len(cidrs))
	for _, c := range cidrs {
		if p, err := netip.ParsePrefix(c); err == nil {
			out = append(out, p)
			continue
		}
		a, err := netip.ParseAddr(c)
		if err != nil {
			return nil, err
		}
		out = append(out, netip.PrefixFrom(a, a.BitLen()))
	}
	return out, nil
}

// Trusted reports whether addr is inside one of the prefixes.
func Trusted(addr netip.Addr, trusted []netip.Prefix) bool {
	addr = addr.Unmap()
	for _, p := range trusted {
		if p.Contains(addr) {
			return true
		}
	}
	return false
}

// PeerAddr extracts the address part of an http.Request.RemoteAddr.
func PeerAddr(remoteAddr string) (netip.Addr, bool) {
	host, _, err := net.SplitHostPort(remoteAddr)
	if err != nil {
		host = remoteAddr
	}
	a, err := netip.ParseAddr(host)
	if err != nil {
		return netip.Addr{}, false
	}
	return a.Unmap(), true
}

// FromRequest returns the client address. xff holds every X-Forwarded-For
// header value of the request (a request may carry the header more than once).
func FromRequest(remoteAddr string, xff []string, trusted []netip.Prefix) (netip.Addr, bool) {
	peer, ok := PeerAddr(remoteAddr)
	if !ok {
		return netip.Addr{}, false
	}
	if !Trusted(peer, trusted) {
		return peer, true // direct client, or an untrusted hop: ignore every header
	}
	var chain []string
	for _, v := range xff {
		for _, part := range strings.Split(v, ",") {
			if p := strings.TrimSpace(part); p != "" {
				chain = append(chain, p)
			}
		}
	}
	client := peer
	for i := len(chain) - 1; i >= 0; i-- {
		a, err := netip.ParseAddr(chain[i])
		if err != nil {
			return client, true // garbage from a trusted hop: stop at the last good address
		}
		client = a.Unmap()
		if !Trusted(client, trusted) {
			return client, true
		}
	}
	return client, true // every hop was ours: the leftmost entry is the best answer
}

The trusted-proxy problem and Laravel TrustProxies Must-know ​

In plain words: The application may believe "X-Forwarded-For" only when the connection came from a proxy it knows. If the connection came from anywhere else, the header is just text from a stranger.

Common misunderstanding: "Trust all proxies with * and the problem is solved." Trusting * means any caller can spoof the headers whenever the app is reachable by a path that bypasses your proxy (a public IP, another port, a misconfigured security group, a debugging tunnel). It is acceptable only when the network guarantees that the app can be reached solely through the proxy, which is what a cloud load balancer in a private subnet gives you. Laravel's documentation suggests * for cloud balancers whose addresses you do not know; combine it with network rules.

Definition: The trusted-proxy rule has three parts. (1) A list of trusted peers (addresses or CIDR ranges). (2) Headers are believed only if the TCP peer is in the list. (3) The client address is the first address, walking the X-Forwarded-For list from the right, that is not itself a trusted proxy. Laravel implements this with the Illuminate\Http\Middleware\TrustProxies middleware: $middleware->trustProxies(at: [...], headers: ...) in bootstrap/app.php; the headers argument is a bit mask built from Request::HEADER_X_FORWARDED_FOR, HEADER_X_FORWARDED_HOST, HEADER_X_FORWARDED_PORT, HEADER_X_FORWARDED_PROTO, HEADER_X_FORWARDED_AWS_ELB and HEADER_FORWARDED. After it runs, $request->ip(), $request->isSecure(), $request->getHost() and url() use the forwarded values.

 1  request from 203.0.113.50 (not trusted) with X-Forwarded-For: 10.1.2.3, X-Forwarded-Proto: https
 2  TrustProxies: peer 203.0.113.50 is not in at: [10.0.0.0/8] -> headers ignored
 3  $request->ip() = 203.0.113.50      $request->isSecure() = false
 4  request from 10.0.0.5 (trusted) with X-Forwarded-For: 198.51.100.7, X-Forwarded-Proto: https
 5  TrustProxies: peer is trusted -> read X-Forwarded-For
 6  $request->ip() = 198.51.100.7      $request->isSecure() = true     url('/login') = https://app.example.com/login

Real scenario: Behind an AWS ALB the app sees every request from the ALB's private address until HEADER_X_FORWARDED_AWS_ELB is trusted; after a deploy to Kubernetes the pod network CIDR changes and at no longer matches, so redirects go to http://; a staging environment trusts * and a pentest sets X-Forwarded-For: 127.0.0.1 to reach an "internal only" route.

StackTrust settingDefault
Laravel 13$middleware->trustProxies(at: ..., headers: ...)No proxies trusted
NGINXset_real_ip_from + real_ip_header X-Forwarded-For + real_ip_recursive onNo addresses trusted
Envoyuse_remote_address and xff_num_trusted_hops on the HTTP connection manageruse_remote_address false
Express (Node)app.set('trust proxy', ...)Off
Go net/httpNo built-in; use a package like clientip belown/a
AWS ALBrouting.http.xff_header_processing.modeappend

Fix / how to use it: the snippets show the Laravel bootstrap, a controller that reports what the framework believes and a feature test that proves an untrusted peer cannot forge the address.

php
<?php

// bootstrap/app.php (Laravel 13): trust only the proxies you operate.
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // Peers allowed to tell us about the real client. Everything else is a client.
        $middleware->trustProxies(
            at: explode(',', (string) env('TRUSTED_PROXIES', '10.0.0.0/8,172.16.0.0/12')),
            // Believe only the headers your edge really sets. Not Forwarded if it never sends it.
            headers: Request::HEADER_X_FORWARDED_FOR
                | Request::HEADER_X_FORWARDED_HOST
                | Request::HEADER_X_FORWARDED_PORT
                | Request::HEADER_X_FORWARDED_PROTO,
        );

        // Reject requests whose Host header is not one of ours (host header attacks).
        $middleware->trustHosts(at: ['^app\.example\.com$']);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })
    ->create();

PROXY protocol Important ​

In plain words: At layer 4 there are no headers, so the proxy sends one extra line at the very start of the connection that says who the real client is.

Common misunderstanding: "Turn on the PROXY protocol on the backend and it will use it when present." The receiver must be told to expect it and must not guess. The specification says: "The receiver MUST NOT start processing the connection before it receives a complete and valid PROXY protocol header", and it explains why guessing is a security hole: it "would open a major security breach by allowing untrusted parties to spoof their connection addresses". If the listener expects the header and the proxy does not send it (or the reverse), every connection fails.

Definition: HAProxy's PROXY protocol prepends a header to the first bytes of a TCP connection. Version 1 is a human-readable line (PROXY TCP4 192.0.2.1 203.0.113.10 56324 443\r\n, at most 107 characters). Version 2 is binary with the 12-byte signature 0D 0A 0D 0A 00 0D 0A 51 55 49 54 0A, an address block, and optional TLV fields (for example the SSL information or an AWS VPC endpoint id). A proxy that already understands the transported protocol (an L7 proxy reusing connections) must not use it on multiplexed connections.

 1  client 198.51.100.7:52341 -> L4 proxy 203.0.113.10:443        TCP connect
 2  L4 proxy -> backend       PROXY TCP4 198.51.100.7 203.0.113.10 52341 443\r\n
 3  L4 proxy -> backend       (then the client's bytes, e.g. TLS ClientHello)
 4  backend                   parses the PROXY line first; its client address is now 198.51.100.7
 5  backend                   a connection without the line from a trusted proxy -> reject

Real scenario: HAProxy send-proxy-v2 to NGINX listen 443 ssl proxy_protocol (with set_real_ip_from and real_ip_header proxy_protocol); an AWS NLB with proxy protocol v2 enabled on the target group; the same setup in front of PostgreSQL or SMTP, where no HTTP header exists at all. Mistake: enabling accept-proxy on a public port, which lets anyone claim any source address.

ProductSendReceive
HAProxysend-proxy, send-proxy-v2 on serveraccept-proxy on bind
NGINXproxy_protocol on in stream serverlisten ... proxy_protocol plus set_real_ip_from
EnvoyProxy protocol upstream transport socketProxy protocol listener filter
AWS NLBTarget group attribute proxy_protocol_v2.enabledn/a
TraefikproxyProtocol on a TCP serviceproxyProtocol.trustedIPs on an entry point

Fix / how to use it: see the HAProxy config below: one TCP tier that sends the header, one HTTP tier that accepts it only on a private port.

cfg
# HAProxy: L4 in front (TCP, PROXY protocol, TLS passthrough) and L7 behind (HTTP).
global
    log stdout format raw local0

defaults
    timeout connect 3s
    timeout client  30s
    timeout server  30s

# L4 tier: do not look inside TLS; tell the next hop who the client was.
frontend tls_in
    mode tcp
    bind :443
    default_backend edge_nginx

backend edge_nginx
    mode tcp
    server nginx1 10.0.0.21:443 send-proxy-v2 check   # PROXY protocol v2 header on every new connection

# L7 tier: HTTP-aware routing, headers and health checks.
frontend http_in
    mode http
    bind :8080 accept-proxy                           # only accept the PROXY header on this trusted port
    option forwardfor                                 # adds X-Forwarded-For with the client address
    http-request set-header X-Forwarded-Proto https
    use_backend api if { path_beg /api/ }
    default_backend web

backend web
    mode http
    balance roundrobin
    option httpchk GET /healthz
    server web1 10.0.1.11:8080 check inter 2s fall 3 rise 2
    server web2 10.0.1.12:8080 check inter 2s fall 3 rise 2

backend api
    mode http
    balance leastconn
    option httpchk GET /healthz
    server api1 10.0.2.11:8080 check

Hop-by-hop headers and Via Important ​

In plain words: Some headers talk only to the next connection, not to the final destination. A proxy must remove them and set its own.

Common misunderstanding: "A proxy copies all headers." A correct proxy drops the hop-by-hop ones. RFC 9110 section 7.6.1 says the Connection field lists connection options that apply only to the immediate recipient; headers named there are removed before forwarding. Forgetting this leaks a client's Connection: keep-alive into an upstream conversation that has its own rules, or breaks Upgrade.

Definition: The standard hop-by-hop set: Connection, Keep-Alive, Proxy-Authenticate, Proxy-Authorization, TE, Trailer, Transfer-Encoding, Upgrade (and the legacy Proxy-Connection), plus every header named in the Connection value. Via is not removed; it is appended by each intermediary: Via: 1.1 edge-1, 1.1 nginx (HTTP version and a pseudonym or host), for diagnostics and loop detection.

 1  client -> proxy   GET /  Connection: keep-alive, X-Secret   X-Secret: 1   Keep-Alive: timeout=5
 2  proxy             remove Connection, Keep-Alive and X-Secret (it was named in Connection)
 3  proxy             add Via: 1.1 edge-1
 4  proxy -> origin   GET /  Via: 1.1 edge-1        (origin never sees X-Secret)
 5  origin -> proxy   200 OK  Connection: close
 6  proxy -> client   200 OK  Via: 1.1 edge-1       (the origin's Connection: close is not copied)

Real scenario: WebSocket upgrade fails behind NGINX because Upgrade and Connection are hop-by-hop and must be set explicitly with proxy_set_header; a Go proxy built by hand with http.Client copies Connection: close and drops upstream keepalive; httputil.ReverseProxy removes hop-by-hop headers before calling Rewrite and ModifyResponse, and re-adds Connection: Upgrade for 101 responses.

HeaderHop-by-hopWhat a proxy does
ConnectionYesRemove; set its own for the upstream
Keep-AliveYesRemove
Proxy-AuthorizationYesConsume at the proxy; never forward to the origin
Transfer-EncodingYesRe-chunk per hop
UpgradeYesPass explicitly for WebSocket only
ViaNoAppend 1.1 name
X-Forwarded-ForNoAppend (trusted) or overwrite (untrusted)
AuthorizationNoEnd-to-end; forward

Fix / how to use it: the Go forward proxy implements RemoveHopByHop and the reverse proxy leans on the standard library; both are tested (TestRemoveHopByHop, TestUntrustedClientCannotForgeForwardingHeaders).

Buffering: request and response Important ​

In plain words: A proxy can either hold a message until it is complete before passing it on (buffering), or pass bytes along as they arrive (streaming). Buffering protects slow application servers from slow clients.

Common misunderstanding: "Buffering only costs memory." Buffering also changes behaviour: server-sent events and live streams stall because the proxy waits for more bytes; a large upload is fully received before the app sees the first byte, so the app cannot reject early; a disk spill can fill a volume. Turning buffering off protects streaming and costs the protection against slow clients.

Definition: NGINX proxy_request_buffering on (default): "the entire request body is read from the client before sending the request to a proxied server"; when off it is sent as it arrives and the request cannot be passed to the next server once sending started. proxy_buffering on (default): the response is read as fast as possible into memory buffers (proxy_buffer_size, proxy_buffers) and, if it does not fit, spilled to a temporary file (proxy_max_temp_file_size). With it off, "the response is passed to a client synchronously, immediately as it is received".

 1  client (3G, 50 KB/s) -> proxy   upload 5 MB                    takes ~100 s
 2  proxy                           request buffering ON: reads all 5 MB first
 3  proxy -> app                    sends 5 MB over a fast LAN in ~50 ms; app worker busy only for ~50 ms
 4  (buffering OFF)  app worker is held ~100 s waiting on the slow client
 5  app -> proxy -> client          response 2 MB: proxy buffers and releases the app in ~20 ms

Real scenario: A PHP-FPM pool exhausted by slow uploads is fixed by request buffering at NGINX; an SSE endpoint stuck until 4 KB accumulates is fixed with proxy_buffering off or the X-Accel-Buffering: no response header; a 2 GB video upload fills /var/lib/nginx/body and the disk; a Go server streaming a log needs FlushInterval set on httputil.ReverseProxy (the sample uses -1, flush immediately).

ProductRequest bodyResponse
NGINXproxy_request_buffering (default on)proxy_buffering (default on), X-Accel-Buffering per response
HAProxyBuffers per request up to tune.bufsize; option http-buffer-request waits for the bodyStreams after headers
EnvoyBuffer filter; per-route stream idle timeoutsStreams by default, flow control by watermarks
Go httputil.ReverseProxyStreams the incoming bodyFlushInterval controls flushing
Caddyrequest_buffers, response_buffers options on reverse_proxyflush_interval

Fix / how to use it: buffer for ordinary APIs and uploads (protects the app tier), unbuffer for streaming and long-polling locations, and cap body sizes at the proxy (client_max_body_size in NGINX) with the same number the application validates.

Timeouts and the 502 vs 504 split Must-know ​

In plain words: Every proxy has several stopwatches: one for connecting to the server, one for sending the request, one for waiting for the answer. When one runs out the proxy gives up and tells the client who failed.

Common misunderstanding: "proxy_read_timeout is the maximum time a request may take." It is not. The NGINX documentation says: "The timeout is set only between two successive read operations, not for the transmission of the whole response." A server that sends one byte every 59 seconds never trips a 60-second read timeout. And the proxy's default (60 s) is usually longer than a user is willing to wait, and often longer than the client's own timeout, so the client gives up first and the proxy logs a 499.

Definition: RFC 9110: 502 Bad Gateway means the proxy "received an invalid response from an inbound server it accessed while attempting to fulfill the request"; 504 Gateway Timeout means it "did not receive a timely response from an upstream server it needed to access". In practice: connect refused or reset = 502, bytes that are not HTTP = 502, connect timeout or read timeout = 504 (NGINX logs these as upstream timed out; the status a client sees is 504). NGINX defaults: proxy_connect_timeout 60s (it "cannot usually exceed 75 seconds"), proxy_send_timeout 60s, proxy_read_timeout 60s.

One request through a reverse proxy: which timer fires, and which status the client seesClientProxyUpstreamrequest + body (client_body_timeout)connect, send, wait first byteclient too slow: 408connect refused or reset: 502no response in time (connect / read timeout): 504invalid or truncated response: 502proxy_connect_timeout 60s, proxy_send_timeout 60s, proxy_read_timeout 60s are NGINX defaults.Read and send timers measure the gap between two operations, not the whole response.Budget rule: client timeout > proxy read timeout > upstream work time, or the proxy returns 504 first.
 1  t=0.0   client -> proxy       POST /export
 2  t=0.0   proxy  -> app         connect ok, request sent
 3  t=30.0  proxy                 proxy_read_timeout 30s: no response bytes -> closes upstream connection
 4  t=30.0  proxy  -> client      504 Gateway Timeout
 5  t=47.2  app                   finishes the export and writes to a closed socket (work done, nobody to tell)
 6  t=47.2  app                   its database transaction committed; the user retries and the export runs twice

Real scenario: A report endpoint takes 70 s and returns 504 from the ALB's 60 s idle timeout (the AWS default); the fix is to make the endpoint asynchronous (202 Accepted and a status URL, see Service Communication), not to raise timeouts forever. A deploy restarts the app and clients see a burst of 502 for a few hundred milliseconds. An application returns a response header of 16 KB, larger than proxy_buffer_size, and NGINX answers 502 and logs "upstream sent too big header". A Go service behind Envoy sets a 15 s server write timeout and the proxy's 30 s route timeout never matters.

TimerNGINXHAProxyEnvoyALB (AWS)
Connect to upstreamproxy_connect_timeout (60s)timeout connectcluster connect_timeoutfixed by the service
Wait for or between response bytesproxy_read_timeout (60s)timeout serverroute timeout, idle_timeoutidle timeout attribute (60 s default)
Send request to upstreamproxy_send_timeout (60s)timeout serverroute timeoutn/a
Slow clientclient_body_timeout, send_timeouttimeout clientstream idle, request timeoutsidle timeout
Tunnel / WebSocket idleproxy_read_timeouttimeout tunnelupgrade idle timeoutidle timeout

Fix / how to use it: order the budgets (client timeout greater than proxy timeout greater than app work) as discussed in Timeouts, Retries & Jitter, propagate a deadline, make long work asynchronous, and treat 504 as "outcome unknown" for non-idempotent requests (the app may still complete the work, so write idempotent endpoints, see API Idempotency). The Go proxy maps timeouts to 504 and everything else to 502 and tests both.

Connection reuse, HTTP/2 front and HTTP/1.1 back Important ​

In plain words: Opening a TCP (and TLS) connection per request is slow. A proxy keeps a pool of open connections to each upstream and reuses them; the client side and the upstream side are separate conversations and can use different HTTP versions.

Common misunderstanding: "If the client speaks HTTP/2 my app sees HTTP/2." Most proxies speak HTTP/2 or HTTP/3 to the client and HTTP/1.1 to the upstream, and that is usually fine: multiplexing exists to save connections across the long, lossy internet path, not across a LAN. One more trap: NGINX's old default of HTTP/1.0 to the upstream had no keepalive; the documentation of proxy_http_version says that before 1.29.7 version 1.0 was the default and since then 1.1 is, and recommends 1.1 or 2 "for use with keepalive connections". Always set it explicitly if you must support older builds.

Definition: Upstream keepalive keeps idle connections open. NGINX: keepalive N; inside upstream, with proxy_http_version 1.1 and proxy_set_header Connection "" on older builds; since 1.29.7 "by default the cache for connections is activated". HAProxy: option http-reuse safe|aggressive|always. Envoy: connection pools per cluster per worker thread, HTTP/1.1 or HTTP/2 chosen by the cluster typed_extension_protocol_options. Go: http.Transport with MaxIdleConnsPerHost (the default is 2, far too low for a proxy) and IdleConnTimeout.

 1  without keepalive: every request pays  TCP handshake (1 RTT) + TLS handshake (1 RTT TLS 1.3) + request
 2  upstream RTT 0.5 ms in the same zone -> 1.5 ms of handshakes on a 5 ms request = 30 % overhead
 3  with keepalive 32: the pool holds idle connections, the 99th request reuses one -> 0 handshakes
 4  danger: the upstream closes idle connections after 5 s, the proxy sends on a connection closed a moment ago -> reset, 502
 5  rule: upstream idle timeout must be longer than the proxy's idle connection lifetime

Real scenario: Sporadic 502 under low traffic with "upstream prematurely closed connection" because Node.js keepAliveTimeout (5 s) is shorter than NGINX's idle connection lifetime; ALB 502 with a target that closes idle connections faster than the ALB's 60 s idle timeout; a Go proxy opening a new connection per request because MaxIdleConnsPerHost is 2 and traffic is 500 rps.

HopTypical protocolWhy
Client to proxyHTTP/2 or HTTP/3 over TLSFewer connections, header compression, multiplexing on a lossy path
Proxy to upstream (same VPC)HTTP/1.1 keepaliveSimple, pooled, no multiplexing gain on a LAN
Proxy to gRPC serviceHTTP/2 (h2c or TLS)gRPC requires HTTP/2 end to end
L4 proxy to anythingOpaquePasses bytes, no version negotiation

Fix / how to use it: the reference NGINX config sets keepalive 32, HTTP/1.1 and Connection ""; the Go proxy sets MaxIdleConnsPerHost: 64, IdleConnTimeout: 90s and ForceAttemptHTTP2: false for HTTP/1.1 upstream. More on HTTP versions: HTTP Evolution.

WebSocket proxying and Upgrade Important ​

In plain words: A WebSocket starts as a normal HTTP request that asks to switch protocols; after the server agrees, the connection becomes a raw two-way pipe. A proxy must carry the request, pass the agreement and then stay out of the way.

Common misunderstanding: "WebSockets just work through any proxy." Because Upgrade and Connection are hop-by-hop, a proxy removes them unless you tell it to pass them. And the proxy still has timeouts: an idle WebSocket looks like a dead upstream connection and is closed at 60 seconds by default in NGINX.

Definition: The client sends Connection: Upgrade and Upgrade: websocket; the server answers 101 Switching Protocols. NGINX: set both headers explicitly (proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";) and, on older builds, proxy_http_version 1.1; the nginx documentation notes that "since the 'Upgrade' is a hop-by-hop header, it is not passed from a client to proxied server" and says that "with forward proxying, clients may use the CONNECT method to circumvent this issue". Go's ReverseProxy handles 101 responses itself. Envoy needs upgrade_configs: [upgrade_type: websocket].

 1  client -> proxy   GET /ws  Connection: Upgrade  Upgrade: websocket  Sec-WebSocket-Key: ...
 2  proxy             sees Upgrade: re-adds Connection: Upgrade and Upgrade: websocket for the upstream
 3  proxy -> app      GET /ws  Connection: upgrade  Upgrade: websocket
 4  app   -> proxy    101 Switching Protocols
 5  proxy -> client   101 Switching Protocols            from here the proxy copies bytes both ways
 6  idle for 60 s     proxy_read_timeout fires -> connection closed; fix with 1h or application pings every 25 s

Real scenario: Laravel Reverb or a chat server drops every connection at exactly 60 seconds; the cure is a longer proxy_read_timeout on the /ws/ location and heartbeat pings. A sticky session is not needed for WebSocket itself (the connection is one TCP stream) but is needed for stateful protocols layered on top (Socket.IO long-polling fallback). Draining on deploy: the old workers keep the open sockets until clients reconnect. More about the transport choice: Real-time: Polling, SSE & WebSockets.

ProductWebSocket setup
NGINXproxy_set_header Upgrade/Connection, long proxy_read_timeout
HAProxyAutomatic with mode http; timeout tunnel for idle length
Envoyupgrade_configs with websocket
Traefik, CaddyAutomatic
AWS ALBNative WebSocket support; the idle timeout applies
CloudflareSupported on all plans; idle behaviour per plan

Fix / how to use it: the /ws/ block in the NGINX config sets the headers and a one hour read timeout; TestUpgradeIsTunnelled proves a 101 upgrade and echo through the Go proxy.

Health checks, retries and ejection Must-know ​

In plain words: The proxy must know which servers are alive. It either probes them (active health check) or learns from failures of real traffic (passive health check) and takes dead ones out of rotation.

Common misunderstanding: "Retrying a failed request on another server is always safe." A request that failed after it was sent may already have been executed. NGINX documents this: "normally, requests with a non-idempotent method (POST, LOCK, PATCH) are not passed to the next server if a request has been sent to an upstream server"; the option non_idempotent explicitly allows it. Safe retries need an idempotent method (or an idempotency key) and a failure that happened before any byte was delivered.

Definition: Active check: the proxy requests GET /healthz at an interval; fall failures mark the server down, rise successes mark it up (HAProxy check inter 2s fall 3 rise 2). Passive check: failures of real requests count (max_fails=2 fail_timeout=10s in NGINX: after two failures within the window the server is skipped for the window). Outlier detection in Envoy ejects hosts returning consecutive 5xx. A health endpoint must report readiness (can serve) separately from liveness (should be restarted), as in Kubernetes.

 1  proxy -> app-2      GET /healthz   200   up
 2  deploy starts: app-2 stops accepting connections
 3  proxy -> app-2      GET /healthz   refused            fail 1 of 3
 4  client -> proxy     GET /cart  -> picks app-2 -> connect refused  (retryable, GET, no bytes sent)
 5  proxy -> app-1      GET /cart  200                     client never sees the failure
 6  proxy               fail 3 of 3 -> app-2 ejected for 10 s; probes continue; rise 2 -> back in rotation

Real scenario: A deploy where the load balancer keeps sending traffic to a pod that is shutting down (needs a preStop delay and connection draining); a health endpoint that checks the database and takes the whole fleet out when the database blips, a self-inflicted outage; "no live upstreams while connecting to upstream" when all are ejected (the Go pool deliberately keeps one in rotation rather than failing everything). Details of load-balancing algorithms and sticky sessions are in Load Balancing.

ProductActivePassiveRetry control
NGINX (open source)No; NGINX Plus health_checkmax_fails, fail_timeoutproxy_next_upstream, proxy_next_upstream_tries
HAProxycheck, option httpchkobserve layer7, on-errorretries, option redispatch
Envoyhealth_checksoutlier_detectionroute retry_policy with retry_on
TraefikhealthCheckcircuit-breaker middlewareretry middleware
Caddyhealth_urifail_duration, max_failslb_try_duration, lb_try_interval
AWS ALBTarget group health checkn/aRetries to another target only on connection failure

Fix / how to use it: the Go rproxy retries only idempotent, body-less requests and only on dial errors, ejects the failing upstream, and runs an active CheckLoop against /healthz.

Graceful reload Important ​

In plain words: A proxy must pick up new config, new certificates or a new binary without cutting requests in flight.

Common misunderstanding: "Restart is the same as reload." A restart closes every connection. A reload starts new workers with the new config and lets old workers finish what they are doing.

Definition: NGINX: send HUP to the master (nginx -s reload): "the master process first checks the syntax validity, then tries to apply new configuration... If this fails, it rolls back changes and continues to work with old configuration" and, on success, "starts new worker processes, and sends messages to old worker processes requesting them to shut down gracefully". Always run nginx -t first. HAProxy: reload starts a new process that takes over the listening sockets and the old one finishes its connections (-sf or master-worker reload). Envoy: hot restart or, more commonly, dynamic xDS updates with no process restart. Caddy: caddy reload or the admin API. Go: http.Server.Shutdown(ctx) stops accepting and drains.

 1  operator            nginx -t            test configuration -> ok
 2  operator            nginx -s reload     HUP to master
 3  master              start new workers with the new config; listening sockets are shared
 4  old workers         stop accepting; finish in-flight requests and open WebSocket connections
 5  new workers         accept new connections immediately
 6  old workers         exit when idle (worker_shutdown_timeout bounds the wait)

Real scenario: A certificate renewed by cron followed by a reload; a pipeline that deploys a config change at peak traffic with zero 502s; a reload that never finishes because a WebSocket keeps an old worker alive for days (set worker_shutdown_timeout); an invalid config reload that is rejected and the old config keeps serving (the reason to prefer reload).

ProductReloadIn-flight requests
NGINXnginx -s reload (HUP)Old workers drain
HAProxysystemctl reload haproxy (master-worker)Old process drains; hard-stop-after bounds it
EnvoyxDS updates; hot restart optionalDrain period per listener
TraefikWatches providers, no reload neededGraceful by design
Caddycaddy reload, admin APIGraceful

Fix / how to use it: validate, reload, watch error rate; for deploys of the application tier use connection draining plus readiness checks so the proxy stops sending new requests before the pod stops.

What else a reverse proxy does: caching, compression, rate limiting, WAF, redirects Important ​

In plain words: Because every request passes through it, the proxy is the cheapest place to do work that every service needs.

Common misunderstanding: "Put everything at the proxy." Business rules, per-user authorization and anything needing the database belong in the application. The proxy handles cross-cutting concerns that need only the HTTP message, and each feature added is also a feature to configure, test and upgrade.

Definition and examples: Response caching (NGINX proxy_cache, Varnish, Cloudflare; see Caching and CDN); compression (gzip or Brotli, saving bytes on text); rate limiting (NGINX limit_req, Envoy local and global rate limit filters; algorithms in Rate Limiting Algorithms); WAF (ModSecurity with the OWASP Core Rule Set, Cloudflare WAF, AWS WAF on an ALB) for generic attack signatures (see OWASP Top 10); request ID injection (X-Request-Id) and trace propagation; redirects from HTTP to HTTPS and canonical hosts; basic authentication or JWT validation at the edge; header normalisation (strip Server, add HSTS); request body limits; static file serving; canary traffic splitting by weight or header.

 1  request  GET /product/42?utm=ad   Cookie: session=...
 2  proxy    WAF rules: no SQLi signature -> pass
 3  proxy    rate limit key (real client IP): 38 req in 1 s > 20 r/s burst 40 -> allow, delay
 4  proxy    cache lookup: key "GET shop.example/product/42" -> HIT (age 12 s, TTL 60 s), no upstream call
 5  proxy    compress response with gzip (text/html), add HSTS and X-Request-Id
 6  proxy -> client  200 OK  X-Cache: HIT

Real scenario: A flash sale protected by a per-client rate limit at the proxy (which depends on the correct client IP, see forwarding headers; a limiter keyed by the balancer's address throttles everyone at once); an API behind AWS WAF blocking known bad bots; a marketing page cached for 60 seconds absorbing a traffic spike so the app tier sees 1 request per minute per page.

DutyNGINXHAProxyEnvoyCloudflare / ALB
Cacheproxy_cacheSmall cache (cache section)HTTP cache filterCloudflare CDN; ALB none
Rate limitlimit_req, limit_connstick-tableRate limit filtersCloudflare rules; ALB with AWS WAF
WAFModSecurity moduleModSecurity SPOEWAF via filters (Coraza, ext_authz)Cloudflare WAF, AWS WAF
Auth at edgeauth_request, JWT in PlusLua, http-request authext_authz, jwt_authnALB OIDC authenticate action
Compressiongzip, Brotli modulecompression algoCompressor filterCloudflare automatic

Fix / how to use it: configure these at the proxy only where the data is available there; and remember the proxy must know the real client IP for any of the per-client features.

Sidecars and API gateways Important ​

In plain words: The same proxy idea shows up at two other scales: a small proxy next to each service (sidecar), and a smart proxy at the edge for all APIs (gateway).

Common misunderstanding: "A service mesh replaces the API gateway" or the reverse. The gateway handles north-south traffic from outside (authentication of external clients, plans, quotas, request shaping); the mesh handles east-west traffic between services (mTLS, retries, telemetry). They overlap in technology (both can run Envoy) and differ in purpose.

Definition: Sidecar: a proxy process deployed in the same pod or host as one application instance, intercepting its inbound and outbound traffic (Envoy "designed to run alongside every application server"; "each application sends and receives messages to and from localhost and is unaware of the network topology"). API gateway: a reverse proxy at the edge with API-specific features (routing by version, authentication, quotas, transformation, developer portal). Mechanics of sidecars: Service Mesh & Sidecar; the decision between gateway, BFF and mesh: API Gateway, BFF & Service Mesh.

 1  external client -> edge gateway   TLS, JWT check, rate limit, route /orders -> orders service
 2  gateway         -> orders pod     request (mTLS to the pod's sidecar)
 3  orders sidecar                    decrypt, enforce policy, record metrics, pass to localhost:8080
 4  orders app      -> sidecar        call to http://payments (resolved by the mesh)
 5  orders sidecar  -> payments sidecar  mTLS, retry policy, timeout, load balancing
 6  payments sidecar -> payments app  plain localhost

Real scenario: Kong, Apigee, AWS API Gateway, Traefik or Envoy Gateway at the edge; Istio or Linkerd sidecars inside; a company whose gateway rejects expired JWTs so services never see them. A forward proxy appears here too: the mesh's egress gateway is a controlled forward proxy for traffic leaving the cluster.

DimensionEdge reverse proxyAPI gatewaySidecar proxy
TrafficInternet to siteInternet to APIsService to service
CountA fewOne logical, several instancesOne per workload instance
Knows aboutHosts and pathsClients, plans, API versionsServices and identities
Trust boundaryOuterOuterInner (mTLS)
Config sourceStatic files, IngressGateway config, control planeMesh control plane

Fix / how to use it: choose by the traffic it handles; see the siblings above. A proxy chain of edge proxy, gateway and sidecar means four to five hops; the forwarding-header rules from this chapter apply at every hop.

Products: what each one is for Must-know ​

In plain words: The same ideas are available in many programs; they differ in config style, where they are strong and how they are run.

Common misunderstanding: "They are interchangeable." They share concepts but not defaults. NGINX closes the upstream with Connection: close unless told otherwise on old builds; HAProxy health checks are on only with check; Envoy trusts no X-Forwarded-For unless use_remote_address is set correctly; Caddy provisions HTTPS automatically. Read the defaults of the one you run.

Definition (one line each): NGINX: web server and reverse proxy, event-driven workers, config files, reload. HAProxy: "a free, very fast and reliable reverse-proxy offering high availability, load balancing, and proxying for TCP and HTTP-based applications". Envoy: "an L7 proxy and communication bus designed for large modern service oriented architectures". Traefik: "an open-source Application Proxy" with dynamic config from providers such as Docker and Kubernetes. Caddy: reverse proxy and web server with automatic HTTPS. Squid: caching forward proxy. Cloudflare: global reverse proxy and CDN run as a service. AWS ALB: managed L7 balancer; AWS NLB: managed L4 balancer with connection tracking.

 1  need                                                  pick
 2  caching forward proxy / egress filter                 Squid (or a cloud secure web gateway)
 3  fast edge reverse proxy, static files, PHP upstream   NGINX
 4  L4 + L7 balancer with strong health checks and ACLs   HAProxy
 5  service mesh data plane, dynamic config, gRPC         Envoy (via Istio, Contour, Envoy Gateway)
 6  containers, auto-discovery, small team                Traefik or Caddy
 7  managed on AWS, no servers to run                     ALB for HTTP, NLB for TCP/TLS passthrough
 8  DDoS absorption, global edge, WAF as a service        Cloudflare or another CDN

Real scenario: A small team runs Caddy for three sites with automatic certificates; a platform team runs NGINX Ingress or Envoy Gateway in Kubernetes; a bank puts HAProxy in front of NGINX for TCP passthrough and PROXY protocol; a startup uses Cloudflare plus an ALB and trusts CF-Connecting-IP only from Cloudflare's published ranges.

ProductTypeConfig modelStrong atWatch out for
NGINXL7 and stream L4Files, reloadEdge, static, PHP-FPM, cachingOpen source health checks are passive; CONNECT unsupported
HAProxyL4 and L7Files, runtime APIBalancing, ACLs, stick tables, PROXY protocolSmaller feature set for web serving
EnvoyL3/L4 and L7xDS APIs, YAMLMesh, observability, gRPC, hot configLearning curve; YAML volume
TraefikL7 and TCPProviders, labelsContainer ingress, Let's EncryptFewer low-level knobs
CaddyL7Caddyfile, JSON, APIAutomatic HTTPS, simple configSmaller ecosystem of rules
SquidForward, cachesquid.conf ACLsEgress control, caching, filteringComplex ACL syntax; not a modern reverse proxy
CloudflareGlobal reverse proxyDashboard, APIDDoS, CDN, WAFTrust ranges, TLS modes, header handling
AWS ALB / NLBL7 / L4 managedConsole, IaCNo servers, integrates with ECS/EKSIdle timeout 60 s default, limited rewriting

Fix / how to use it: the Envoy snippet below is a minimal L7 reverse proxy; note use_remote_address: true, WebSocket upgrade, cluster health checks and a connect timeout.

yaml
# Envoy as an L7 reverse proxy: one listener, one route, one cluster with health checks.
static_resources:
  listeners:
  - name: ingress
    address: { socket_address: { address: 0.0.0.0, port_value: 8080 } }
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          stat_prefix: ingress
          use_remote_address: true          # trust the TCP peer, not the client's X-Forwarded-For
          xff_num_trusted_hops: 0
          upgrade_configs:
          - upgrade_type: websocket
          route_config:
            virtual_hosts:
            - name: app
              domains: ["app.example.com"]
              routes:
              - match: { prefix: "/" }
                route: { cluster: app, timeout: 30s }
          http_filters:
          - name: envoy.filters.http.router
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
  clusters:
  - name: app
    type: STRICT_DNS
    connect_timeout: 3s
    health_checks:
    - timeout: 1s
      interval: 5s
      unhealthy_threshold: 3
      healthy_threshold: 2
      http_health_check: { path: /healthz }
    load_assignment:
      cluster_name: app
      endpoints:
      - lb_endpoints:
        - endpoint: { address: { socket_address: { address: 10.0.1.11, port_value: 8080 } } }
        - endpoint: { address: { socket_address: { address: 10.0.1.12, port_value: 8080 } } }

Mechanics ​

The exact knobs ​

KnobProductDefaultWhat it controls
proxy_connect_timeoutNGINX60sTime to establish the upstream connection; cannot usually exceed 75 s
proxy_send_timeoutNGINX60sGap between two write operations to the upstream
proxy_read_timeoutNGINX60sGap between two read operations from the upstream
proxy_http_versionNGINX1.1 since 1.29.7, 1.0 beforeHTTP version to the upstream; keepalive needs 1.1
proxy_request_bufferingNGINXonRead the whole request body before contacting the upstream
proxy_bufferingNGINXonBuffer the upstream response before sending it to the client
proxy_next_upstreamNGINXerror timeoutWhich failures pass the request to the next server; POST/PATCH/LOCK only with non_idempotent
client_max_body_sizeNGINX1mMaximum request body; larger gives 413
timeout connect/client/serverHAProxyunset (set them)Per-phase timers; timeout tunnel for upgraded connections
option forwardforHAProxyoffAdds X-Forwarded-For
use_remote_addressEnvoyfalseTrust the TCP peer, not the client's XFF, as the client address
xff_num_trusted_hopsEnvoy0Number of trusted proxies in front of the edge
routing.http.xff_header_processing.modeAWS ALBappendAppend, preserve or remove X-Forwarded-For
idle timeoutAWS ALB60 sClose a connection idle in both directions
MaxIdleConnsPerHostGo http.Transport2Idle upstream connections per host; raise it for a proxy
FlushIntervalGo httputil.ReverseProxy0How often to flush while copying the response; negative flushes immediately

Status codes a proxy produces ​

StatusMeaningTypical causeRetry?
400Proxy could not parse the requestBad header, request smuggling attemptNo
407Proxy authentication requiredForward proxy without credentialsAfter adding credentials
408Client too slow sending the requestMobile network, slowlorisYes, the client decides
413Body larger than the proxy limitclient_max_body_sizeNo, change the request
429Rate limit at the proxylimit_req, WAF ruleAfter backoff (Retry-After)
499NGINX-only: client closed the connectionUser navigated away, client timeout shorter than proxyNo
502 Bad GatewayInvalid response or connection failure to the upstreamRefused, reset, crash, protocol mismatchIdempotent only
503No upstream available or deliberately sheddingAll ejected, maintenance modeYes with backoff
504 Gateway TimeoutUpstream did not answer in timeSlow query, long export, GC pauseOutcome unknown; idempotent only

Log lines you will actually see ​

WhereLineMeaning
NGINX error logconnect() failed (111: Connection refused) while connecting to upstreamNothing listens on the upstream port: 502
NGINX error logupstream timed out (110: Connection timed out) while reading response header from upstreamproxy_read_timeout fired: 504
NGINX error logupstream prematurely closed connection while reading response header from upstreamUpstream closed (crash, idle keepalive race): 502
NGINX error logno live upstreams while connecting to upstreamEvery server in the group is marked down: 502
NGINX error logupstream sent too big header while reading response header from upstreamResponse header larger than proxy_buffer_size: 502
NGINX error logclient intended to send too large bodyBody above client_max_body_size: 413
HAProxy logtermination flags sH, sC, SC, cDServer timeout waiting for headers, server timeout connecting, server refused, client timeout in data phase
Envoy access logresponse flags UF, UT, UC, NRUpstream connection failure, upstream request timeout, upstream connection termination, no route
Go proxyhttp: proxy error: dial tcp 10.0.1.11:8080: connect: connection refusedThe default ErrorHandler message when the upstream is down

The client address arithmetic ​

 1  header at the app:            X-Forwarded-For: 203.0.113.99, 198.51.100.7, 10.0.0.4
 2  TCP peer:                     10.0.0.9   (trusted: in 10.0.0.0/8)
 3  walk from the right:          10.0.0.4   trusted proxy -> skip
 4                                198.51.100.7   not a trusted proxy -> this is the client
 5  everything left of it is the client's own claim -> ignore
 6  untrusted peer: if the peer is not in the list, ignore the header entirely and use the peer

What a request costs ​

Back-of-envelope, labelled as estimate: a proxy hop inside one availability zone adds roughly 0.1 to 1 ms of latency and a few percent CPU; a new TLS 1.3 connection costs one round trip plus public-key operations; so a proxy terminating TLS for clients far away (50 ms RTT) saves the application tier every handshake and keeps a warm pool (RTT 0.5 ms) to it. The number to remember is the ratio: handshakes at the edge are paid by the proxy once per client connection; handshakes upstream are paid once per pooled connection, not once per request.

Go ​

Example: a reverse proxy, a client-address resolver and a forward proxy ​

The Go code is three small packages and their tests. before is the naive client-IP function that trusts the first X-Forwarded-For entry (bad design, shown above). clientip is the right-to-left walk. rproxy builds on httputil.ReverseProxy with Rewrite (not the deprecated Director). fproxy is a forward proxy with CONNECT.

go
package clientip

import (
	"net/http"
	"net/netip"
	"testing"

	"academy/proxies-forward-reverse/before"
)

func TestFromRequest(t *testing.T) {
	trusted, err := Parse("10.0.0.0/8", "192.0.2.10")
	if err != nil {
		t.Fatal(err)
	}
	cases := []struct {
		name   string
		remote string
		xff    []string
		want   string
	}{
		{"direct client ignores header", "198.51.100.7:5000", []string{"203.0.113.99"}, "198.51.100.7"},
		{"one trusted proxy", "10.0.0.5:4444", []string{"198.51.100.7"}, "198.51.100.7"},
		{"two trusted hops", "10.0.0.5:4444", []string{"198.51.100.7, 10.1.1.1"}, "198.51.100.7"},
		{"client forged the left side", "10.0.0.5:4444", []string{"203.0.113.99, 198.51.100.7"}, "198.51.100.7"},
		{"split header lines", "10.0.0.5:4444", []string{"203.0.113.99", "198.51.100.7"}, "198.51.100.7"},
		{"garbage entry stops the walk", "10.0.0.5:4444", []string{"not-an-ip, 10.9.9.9"}, "10.9.9.9"},
		{"all hops trusted", "10.0.0.5:4444", []string{"10.2.2.2"}, "10.2.2.2"},
		{"ipv6 mapped peer", "[::ffff:10.0.0.5]:80", []string{"2001:db8::1"}, "2001:db8::1"},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, ok := FromRequest(c.remote, c.xff, trusted)
			if !ok || got != netip.MustParseAddr(c.want) {
				t.Fatalf("got %v ok=%v want %s", got, ok, c.want)
			}
		})
	}
}

func TestNaiveVersionIsSpoofable(t *testing.T) {
	r, _ := http.NewRequest(http.MethodGet, "http://example.test/", nil)
	r.RemoteAddr = "198.51.100.7:5000"
	r.Header.Set("X-Forwarded-For", "203.0.113.99")
	if got := before.ClientIP(r); got != "203.0.113.99" {
		t.Fatalf("expected the naive version to be fooled, got %s", got)
	}
	trusted, _ := Parse("10.0.0.0/8")
	got, _ := FromRequest(r.RemoteAddr, r.Header.Values("X-Forwarded-For"), trusted)
	if got.String() != "198.51.100.7" {
		t.Fatalf("trusted-proxy version must ignore the header, got %s", got)
	}
}
go
// Package rproxy is a small reverse proxy built on httputil.ReverseProxy.
//
// It shows the decisions a real edge proxy makes: which forwarding headers
// to trust, how to bound every phase with a timeout, how to retry safely,
// how to map upstream failures to 502 and 504, and how to eject a dead upstream.
package rproxy

import (
	"context"
	"errors"
	"fmt"
	"net"
	"net/http"
	"net/http/httputil"
	"net/netip"
	"net/url"
	"sync"
	"time"

	"academy/proxies-forward-reverse/clientip"
)

// Config holds everything the proxy needs.
type Config struct {
	Upstreams             []*url.URL
	TrustedProxies        []netip.Prefix // peers whose X-Forwarded-* headers we believe
	Pseudonym             string         // name written into the Via header
	DialTimeout           time.Duration  // like nginx proxy_connect_timeout
	ResponseHeaderTimeout time.Duration  // time to first response byte, like proxy_read_timeout for the header
	MaxAttempts           int            // total tries for a retryable request
	EjectFor              time.Duration  // how long a failing upstream sits out
}

// Proxy is an http.Handler plus the upstream pool behind it.
type Proxy struct {
	handler http.Handler
	pool    *pool
}

// New builds the proxy.
func New(cfg Config) (*Proxy, error) {
	if len(cfg.Upstreams) == 0 {
		return nil, errors.New("rproxy: no upstreams")
	}
	if cfg.DialTimeout == 0 {
		cfg.DialTimeout = 3 * time.Second
	}
	if cfg.ResponseHeaderTimeout == 0 {
		cfg.ResponseHeaderTimeout = 30 * time.Second
	}
	if cfg.MaxAttempts == 0 {
		cfg.MaxAttempts = 2
	}
	if cfg.EjectFor == 0 {
		cfg.EjectFor = 10 * time.Second
	}
	if cfg.Pseudonym == "" {
		cfg.Pseudonym = "edge"
	}
	p := &Proxy{pool: newPool(cfg.Upstreams, cfg.EjectFor)}

	base := &http.Transport{
		DialContext:           (&net.Dialer{Timeout: cfg.DialTimeout, KeepAlive: 30 * time.Second}).DialContext,
		MaxIdleConns:          256,
		MaxIdleConnsPerHost:   64, // keepalive upstream: reuse connections instead of one dial per request
		IdleConnTimeout:       90 * time.Second,
		ResponseHeaderTimeout: cfg.ResponseHeaderTimeout,
		ForceAttemptHTTP2:     false, // HTTP/1.1 upstream; the client side may still speak HTTP/2
	}
	rp := &httputil.ReverseProxy{
		Rewrite:        func(pr *httputil.ProxyRequest) { rewrite(pr, cfg) },
		Transport:      &retryTransport{base: base, pool: p.pool, attempts: cfg.MaxAttempts},
		ErrorHandler:   errorHandler,
		ModifyResponse: func(resp *http.Response) error { resp.Header.Add("Via", "1.1 "+cfg.Pseudonym); return nil },
		FlushInterval:  -1, // flush immediately: needed for SSE and streaming responses
	}
	p.handler = rp
	return p, nil
}

// ServeHTTP implements http.Handler.
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { p.handler.ServeHTTP(w, r) }

// rewrite builds the outbound request. ReverseProxy has already removed
// hop-by-hop headers and the Forwarded / X-Forwarded-* headers from Out.
func rewrite(pr *httputil.ProxyRequest, cfg Config) {
	in, out := pr.In, pr.Out
	peerTrusted := false
	if peer, ok := clientip.PeerAddr(in.RemoteAddr); ok {
		peerTrusted = clientip.Trusted(peer, cfg.TrustedProxies)
	}
	if peerTrusted {
		// An upstream proxy of ours spoke: keep its chain and append the peer.
		out.Header["X-Forwarded-For"] = in.Header["X-Forwarded-For"]
	}
	pr.SetXForwarded() // appends the peer address, sets X-Forwarded-Host and X-Forwarded-Proto
	if peerTrusted {
		if proto := in.Header.Get("X-Forwarded-Proto"); proto != "" {
			out.Header.Set("X-Forwarded-Proto", proto) // TLS ended at the tier before us
		}
	}
	out.Header.Del("X-Real-IP") // never forward a value the client could have set
	if ip, ok := clientip.FromRequest(in.RemoteAddr, in.Header.Values("X-Forwarded-For"), cfg.TrustedProxies); ok {
		out.Header.Set("X-Real-IP", ip.String())
	}
	out.Header.Add("Via", fmt.Sprintf("%d.%d %s", in.ProtoMajor, in.ProtoMinor, cfg.Pseudonym))
	// Host is preserved (out is a clone of in), so the app sees the public host name.
}

// errorHandler maps proxy failures to the status codes RFC 9110 defines.
func errorHandler(w http.ResponseWriter, r *http.Request, err error) {
	var ne net.Error
	switch {
	case errors.Is(err, context.Canceled):
		w.WriteHeader(499) // client went away; nginx logs the same non-standard code
	case errors.Is(err, context.DeadlineExceeded), errors.As(err, &ne) && ne.Timeout():
		http.Error(w, "upstream timed out", http.StatusGatewayTimeout) // 504
	default:
		http.Error(w, "bad gateway", http.StatusBadGateway) // 502: refused, reset, invalid response
	}
}

// retryTransport picks an upstream per attempt and retries only when that is safe.
type retryTransport struct {
	base     http.RoundTripper
	pool     *pool
	attempts int
}

func (t *retryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	var lastErr error
	for i := 0; i < t.attempts; i++ {
		up := t.pool.pick()
		if up == nil {
			return nil, errors.New("rproxy: no healthy upstream")
		}
		out := req.Clone(req.Context())
		out.URL.Scheme, out.URL.Host = up.url.Scheme, up.url.Host
		resp, err := t.base.RoundTrip(out)
		if err == nil {
			return resp, nil
		}
		lastErr = err
		if !retryable(req, err) {
			return nil, err
		}
		t.pool.eject(up) // the connection never opened: take this upstream out for a while
	}
	return nil, lastErr
}

// retryable allows a retry only for idempotent requests without a body, and
// only when the failure happened while dialing, so no byte reached the upstream.
func retryable(req *http.Request, err error) bool {
	switch req.Method {
	case http.MethodGet, http.MethodHead, http.MethodOptions:
	default:
		return false
	}
	if req.Body != nil && req.Body != http.NoBody {
		return false
	}
	var oe *net.OpError
	return errors.As(err, &oe) && oe.Op == "dial"
}

type upstream struct {
	url       *url.URL
	downUntil time.Time
}

type pool struct {
	mu       sync.Mutex
	ups      []*upstream
	next     int
	ejectFor time.Duration
}

func newPool(urls []*url.URL, ejectFor time.Duration) *pool {
	p := &pool{ejectFor: ejectFor}
	for _, u := range urls {
		p.ups = append(p.ups, &upstream{url: u})
	}
	return p
}

// pick is round robin over upstreams that are not ejected. If all are
// ejected it still returns one, so a bad health signal cannot cause a total outage.
func (p *pool) pick() *upstream {
	p.mu.Lock()
	defer p.mu.Unlock()
	now := time.Now()
	for i := 0; i < len(p.ups); i++ {
		u := p.ups[(p.next+i)%len(p.ups)]
		if now.After(u.downUntil) {
			p.next = (p.next + i + 1) % len(p.ups)
			return u
		}
	}
	u := p.ups[p.next%len(p.ups)]
	p.next++
	return u
}

func (p *pool) eject(u *upstream) {
	p.mu.Lock()
	u.downUntil = time.Now().Add(p.ejectFor)
	p.mu.Unlock()
}

func (p *pool) set(u *upstream, up bool) {
	p.mu.Lock()
	if up {
		u.downUntil = time.Time{}
	} else {
		u.downUntil = time.Now().Add(p.ejectFor)
	}
	p.mu.Unlock()
}

// CheckLoop probes GET /healthz on every upstream until ctx ends (active health check).
func (p *Proxy) CheckLoop(ctx context.Context, every time.Duration) {
	client := &http.Client{Timeout: time.Second}
	t := time.NewTicker(every)
	defer t.Stop()
	for {
		for _, u := range p.pool.ups {
			ok := false
			if resp, err := client.Get(u.url.String() + "/healthz"); err == nil {
				ok = resp.StatusCode == http.StatusOK
				resp.Body.Close()
			}
			p.pool.set(u, ok)
		}
		select {
		case <-ctx.Done():
			return
		case <-t.C:
		}
	}
}

// Healthy reports how many upstreams are currently in rotation.
func (p *Proxy) Healthy() int {
	p.pool.mu.Lock()
	defer p.pool.mu.Unlock()
	n := 0
	for _, u := range p.pool.ups {
		if time.Now().After(u.downUntil) {
			n++
		}
	}
	return n
}
go
package rproxy

import (
	"bufio"
	"context"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"academy/proxies-forward-reverse/clientip"
)

func mustURL(t *testing.T, s string) *url.URL {
	t.Helper()
	u, err := url.Parse(s)
	if err != nil {
		t.Fatal(err)
	}
	return u
}

// echoHeaders replies with the headers the upstream saw.
func echoHeaders(w http.ResponseWriter, r *http.Request) {
	for _, k := range []string{"X-Forwarded-For", "X-Forwarded-Proto", "X-Forwarded-Host", "X-Real-Ip", "Via", "Connection", "Keep-Alive"} {
		w.Header().Set("Seen-"+k, r.Header.Get(k))
	}
	w.Header().Set("Seen-Host", r.Host)
}

func newProxy(t *testing.T, cfg Config) *httptest.Server {
	t.Helper()
	p, err := New(cfg)
	if err != nil {
		t.Fatal(err)
	}
	srv := httptest.NewServer(p)
	t.Cleanup(srv.Close)
	return srv
}

func TestUntrustedClientCannotForgeForwardingHeaders(t *testing.T) {
	up := httptest.NewServer(http.HandlerFunc(echoHeaders))
	defer up.Close()
	srv := newProxy(t, Config{Upstreams: []*url.URL{mustURL(t, up.URL)}, Pseudonym: "edge-1"})

	req, _ := http.NewRequest(http.MethodGet, srv.URL, nil)
	req.Header.Set("X-Forwarded-For", "203.0.113.99")
	req.Header.Set("X-Forwarded-Proto", "https")
	req.Header.Set("X-Real-IP", "203.0.113.99")
	req.Header.Set("Connection", "keep-alive, X-Secret")
	req.Header.Set("X-Secret", "hop")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()
	if got := resp.Header.Get("Seen-X-Forwarded-For"); got != "127.0.0.1" {
		t.Fatalf("XFF must hold only the peer, got %q", got)
	}
	if got := resp.Header.Get("Seen-X-Forwarded-Proto"); got != "http" {
		t.Fatalf("proto must be what this hop saw, got %q", got)
	}
	if got := resp.Header.Get("Seen-X-Real-Ip"); got != "127.0.0.1" {
		t.Fatalf("X-Real-IP must be recomputed, got %q", got)
	}
	if got := resp.Header.Get("Seen-Via"); !strings.HasSuffix(got, " edge-1") {
		t.Fatalf("Via missing: %q", got)
	}
	if got := resp.Header.Get("Via"); !strings.HasSuffix(got, " edge-1") {
		t.Fatalf("response Via missing: %q", got)
	}
}

func TestTrustedPeerChainIsKept(t *testing.T) {
	up := httptest.NewServer(http.HandlerFunc(echoHeaders))
	defer up.Close()
	trusted, _ := clientip.Parse("127.0.0.0/8")
	srv := newProxy(t, Config{Upstreams: []*url.URL{mustURL(t, up.URL)}, TrustedProxies: trusted})

	req, _ := http.NewRequest(http.MethodGet, srv.URL, nil)
	req.Header.Set("X-Forwarded-For", "198.51.100.7")
	req.Header.Set("X-Forwarded-Proto", "https")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()
	if got := resp.Header.Get("Seen-X-Forwarded-For"); got != "198.51.100.7, 127.0.0.1" {
		t.Fatalf("chain: %q", got)
	}
	if got := resp.Header.Get("Seen-X-Forwarded-Proto"); got != "https" {
		t.Fatalf("proto: %q", got)
	}
	if got := resp.Header.Get("Seen-X-Real-Ip"); got != "198.51.100.7" {
		t.Fatalf("real ip: %q", got)
	}
}

func deadURL(t *testing.T) *url.URL {
	t.Helper()
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	addr := l.Addr().String()
	l.Close() // nothing listens here any more: connection refused
	return mustURL(t, "http://"+addr)
}

func TestRetryOnDialFailureForGET(t *testing.T) {
	good := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") }))
	defer good.Close()
	srv := newProxy(t, Config{Upstreams: []*url.URL{deadURL(t), mustURL(t, good.URL)}, MaxAttempts: 2})
	for i := 0; i < 4; i++ { // round robin hits the dead upstream first on some requests
		resp, err := http.Get(srv.URL)
		if err != nil {
			t.Fatal(err)
		}
		b, _ := io.ReadAll(resp.Body)
		resp.Body.Close()
		if resp.StatusCode != 200 || string(b) != "ok" {
			t.Fatalf("request %d: %d %q", i, resp.StatusCode, b)
		}
	}
}

func TestNoRetryForPOSTReturns502(t *testing.T) {
	srv := newProxy(t, Config{Upstreams: []*url.URL{deadURL(t)}, MaxAttempts: 3})
	resp, err := http.Post(srv.URL, "text/plain", strings.NewReader("x"))
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()
	if resp.StatusCode != http.StatusBadGateway {
		t.Fatalf("want 502, got %d", resp.StatusCode)
	}
}

func TestSlowUpstreamReturns504(t *testing.T) {
	slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		select {
		case <-time.After(2 * time.Second):
		case <-r.Context().Done():
		}
	}))
	defer slow.Close()
	srv := newProxy(t, Config{Upstreams: []*url.URL{mustURL(t, slow.URL)}, ResponseHeaderTimeout: 100 * time.Millisecond})
	resp, err := http.Get(srv.URL)
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()
	if resp.StatusCode != http.StatusGatewayTimeout {
		t.Fatalf("want 504, got %d", resp.StatusCode)
	}
}

func TestActiveHealthCheckEjectsFailingUpstream(t *testing.T) {
	var healthy atomic.Bool
	healthy.Store(true)
	up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/healthz" && !healthy.Load() {
			w.WriteHeader(http.StatusServiceUnavailable)
			return
		}
		io.WriteString(w, "ok")
	}))
	defer up.Close()
	p, err := New(Config{Upstreams: []*url.URL{mustURL(t, up.URL)}, EjectFor: time.Minute})
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	healthy.Store(false)
	go p.CheckLoop(ctx, 20*time.Millisecond)
	deadline := time.Now().Add(2 * time.Second)
	for p.Healthy() != 0 && time.Now().Before(deadline) {
		time.Sleep(10 * time.Millisecond)
	}
	if p.Healthy() != 0 {
		t.Fatal("upstream should have been ejected")
	}
}

// TestUpgradeIsTunnelled shows that ReverseProxy handles 101 Switching Protocols:
// Connection and Upgrade are hop-by-hop, yet the proxy re-adds them for the upstream.
func TestUpgradeIsTunnelled(t *testing.T) {
	up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if !strings.EqualFold(r.Header.Get("Upgrade"), "echo") {
			http.Error(w, "no upgrade", http.StatusBadRequest)
			return
		}
		conn, rw, err := w.(http.Hijacker).Hijack()
		if err != nil {
			return
		}
		defer conn.Close()
		rw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: echo\r\nConnection: Upgrade\r\n\r\n")
		rw.Flush()
		buf := make([]byte, 4)
		if _, err := io.ReadFull(rw, buf); err == nil {
			conn.Write(buf)
		}
	}))
	defer up.Close()
	srv := newProxy(t, Config{Upstreams: []*url.URL{mustURL(t, up.URL)}})

	conn, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://"))
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()
	conn.SetDeadline(time.Now().Add(3 * time.Second))
	io.WriteString(conn, "GET /ws HTTP/1.1\r\nHost: example.test\r\nConnection: Upgrade\r\nUpgrade: echo\r\n\r\n")
	br := bufio.NewReader(conn)
	resp, err := http.ReadResponse(br, nil)
	if err != nil {
		t.Fatal(err)
	}
	if resp.StatusCode != http.StatusSwitchingProtocols {
		t.Fatalf("want 101, got %d", resp.StatusCode)
	}
	io.WriteString(conn, "ping")
	got := make([]byte, 4)
	if _, err := io.ReadFull(br, got); err != nil || string(got) != "ping" {
		t.Fatalf("echo through tunnel failed: %q %v", got, err)
	}
}
go
// Package fproxy is a minimal forward (egress) proxy: it answers CONNECT for
// HTTPS tunnels and absolute-form requests for plain HTTP, and applies an
// allow-list so servers can only reach destinations someone approved.
package fproxy

import (
	"crypto/subtle"
	"io"
	"net"
	"net/http"
	"strings"
	"sync"
	"time"
)

// Proxy is an http.Handler for clients configured with this proxy.
type Proxy struct {
	Allow       func(hostport string) bool // egress policy; nil denies everything
	Credentials string                     // "user:pass" for Basic proxy auth; empty disables auth
	DialTimeout time.Duration
	Transport   *http.Transport // used for plain HTTP; nil means a default with Proxy disabled
	once        sync.Once
}

// hopByHop lists the headers a proxy must not forward (RFC 9110 section 7.6.1 plus legacy names).
var hopByHop = []string{
	"Connection", "Proxy-Connection", "Keep-Alive", "Proxy-Authenticate",
	"Proxy-Authorization", "Te", "Trailer", "Transfer-Encoding", "Upgrade",
}

// RemoveHopByHop deletes the standard hop-by-hop headers and every header named in Connection.
func RemoveHopByHop(h http.Header) {
	for _, v := range h.Values("Connection") {
		for _, name := range strings.Split(v, ",") {
			if name = strings.TrimSpace(name); name != "" {
				h.Del(name)
			}
		}
	}
	for _, name := range hopByHop {
		h.Del(name)
	}
}

func (p *Proxy) init() {
	p.once.Do(func() {
		if p.DialTimeout == 0 {
			p.DialTimeout = 5 * time.Second
		}
		if p.Transport == nil {
			p.Transport = &http.Transport{Proxy: nil, MaxIdleConnsPerHost: 16, IdleConnTimeout: 90 * time.Second}
		}
	})
}

func (p *Proxy) authorised(r *http.Request) bool {
	if p.Credentials == "" {
		return true
	}
	user, pass, ok := parseBasic(r.Header.Get("Proxy-Authorization"))
	return ok && subtle.ConstantTimeCompare([]byte(user+":"+pass), []byte(p.Credentials)) == 1
}

func parseBasic(h string) (user, pass string, ok bool) {
	// Reuse net/http's parser by wrapping the value in a throwaway request.
	r := &http.Request{Header: http.Header{"Authorization": {h}}}
	return r.BasicAuth()
}

// ServeHTTP implements http.Handler.
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	p.init()
	if !p.authorised(r) {
		w.Header().Set("Proxy-Authenticate", `Basic realm="egress"`)
		http.Error(w, "proxy authentication required", http.StatusProxyAuthRequired) // 407
		return
	}
	if r.Method == http.MethodConnect {
		p.connect(w, r)
		return
	}
	p.forward(w, r)
}

// connect opens a blind tunnel: after "200 Connection Established" the proxy
// only copies bytes, so TLS stays end to end between client and origin.
func (p *Proxy) connect(w http.ResponseWriter, r *http.Request) {
	target := r.Host // authority-form: host:port
	if p.Allow == nil || !p.Allow(target) {
		http.Error(w, "destination not allowed", http.StatusForbidden)
		return
	}
	upstream, err := net.DialTimeout("tcp", target, p.DialTimeout)
	if err != nil {
		http.Error(w, "cannot reach destination", http.StatusBadGateway)
		return
	}
	hj, ok := w.(http.Hijacker)
	if !ok {
		upstream.Close()
		http.Error(w, "hijacking unsupported", http.StatusInternalServerError)
		return
	}
	client, _, err := hj.Hijack()
	if err != nil {
		upstream.Close()
		return
	}
	io.WriteString(client, "HTTP/1.1 200 Connection Established\r\n\r\n")
	var wg sync.WaitGroup
	wg.Add(2)
	pipe := func(dst, src net.Conn) {
		defer wg.Done()
		io.Copy(dst, src)
		if tc, ok := dst.(*net.TCPConn); ok {
			tc.CloseWrite() // propagate half-close so the peer sees EOF
		}
	}
	go pipe(upstream, client)
	go pipe(client, upstream)
	wg.Wait()
	client.Close()
	upstream.Close()
}

// forward handles absolute-form requests such as "GET http://host/path HTTP/1.1".
func (p *Proxy) forward(w http.ResponseWriter, r *http.Request) {
	if !r.URL.IsAbs() {
		http.Error(w, "a forward proxy needs an absolute-form request target", http.StatusBadRequest)
		return
	}
	if p.Allow == nil || !p.Allow(r.URL.Host) {
		http.Error(w, "destination not allowed", http.StatusForbidden)
		return
	}
	out := r.Clone(r.Context())
	out.RequestURI = ""
	RemoveHopByHop(out.Header)
	out.Header.Add("Via", "1.1 egress")
	resp, err := p.Transport.RoundTrip(out)
	if err != nil {
		http.Error(w, "bad gateway", http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()
	RemoveHopByHop(resp.Header)
	for k, vs := range resp.Header {
		for _, v := range vs {
			w.Header().Add(k, v)
		}
	}
	w.Header().Add("Via", "1.1 egress")
	w.WriteHeader(resp.StatusCode)
	io.Copy(w, resp.Body)
}
go
package fproxy

import (
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"time"
)

func TestRemoveHopByHop(t *testing.T) {
	h := http.Header{}
	h.Set("Connection", "close, X-Private")
	h.Set("X-Private", "1")
	h.Set("Keep-Alive", "timeout=5")
	h.Set("Proxy-Authorization", "Basic abc")
	h.Set("Accept", "text/html")
	RemoveHopByHop(h)
	if len(h) != 1 || h.Get("Accept") == "" {
		t.Fatalf("only end-to-end headers may remain: %v", h)
	}
}

func startEcho(t *testing.T) string {
	t.Helper()
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { l.Close() })
	go func() {
		for {
			c, err := l.Accept()
			if err != nil {
				return
			}
			go func() { defer c.Close(); io.Copy(c, c) }()
		}
	}()
	return l.Addr().String()
}

func TestConnectTunnelsBytes(t *testing.T) {
	echo := startEcho(t)
	proxy := httptest.NewServer(&Proxy{Allow: func(hp string) bool { return hp == echo }})
	defer proxy.Close()

	c, err := net.Dial("tcp", strings.TrimPrefix(proxy.URL, "http://"))
	if err != nil {
		t.Fatal(err)
	}
	defer c.Close()
	c.SetDeadline(time.Now().Add(3 * time.Second))
	io.WriteString(c, "CONNECT "+echo+" HTTP/1.1\r\nHost: "+echo+"\r\n\r\n")
	buf := make([]byte, len("HTTP/1.1 200 Connection Established\r\n\r\n"))
	if _, err := io.ReadFull(c, buf); err != nil || !strings.HasPrefix(string(buf), "HTTP/1.1 200") {
		t.Fatalf("handshake: %q %v", buf, err)
	}
	io.WriteString(c, "hello")
	got := make([]byte, 5)
	if _, err := io.ReadFull(c, got); err != nil || string(got) != "hello" {
		t.Fatalf("tunnel echo: %q %v", got, err)
	}
}

func TestConnectDeniedByPolicy(t *testing.T) {
	proxy := httptest.NewServer(&Proxy{Allow: func(string) bool { return false }})
	defer proxy.Close()
	c, _ := net.Dial("tcp", strings.TrimPrefix(proxy.URL, "http://"))
	defer c.Close()
	io.WriteString(c, "CONNECT 203.0.113.9:443 HTTP/1.1\r\nHost: 203.0.113.9:443\r\n\r\n")
	b := make([]byte, 12)
	io.ReadFull(c, b)
	if !strings.HasPrefix(string(b), "HTTP/1.1 403") {
		t.Fatalf("want 403, got %q", b)
	}
}

func TestPlainHTTPThroughProxyAddsVia(t *testing.T) {
	origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Saw-Via", r.Header.Get("Via"))
		w.Header().Set("X-Saw-Proxy-Auth", r.Header.Get("Proxy-Authorization"))
		io.WriteString(w, "origin")
	}))
	defer origin.Close()
	host := strings.TrimPrefix(origin.URL, "http://")
	proxy := httptest.NewServer(&Proxy{Allow: func(hp string) bool { return hp == host }, Credentials: "svc:s3cret"})
	defer proxy.Close()

	pu, _ := url.Parse(proxy.URL)
	pu.User = url.UserPassword("svc", "s3cret")
	client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(pu)}}
	resp, err := client.Get(origin.URL)
	if err != nil {
		t.Fatal(err)
	}
	body, _ := io.ReadAll(resp.Body)
	resp.Body.Close()
	if string(body) != "origin" || resp.Header.Get("X-Saw-Via") != "1.1 egress" {
		t.Fatalf("body=%q via=%q", body, resp.Header.Get("X-Saw-Via"))
	}
	if resp.Header.Get("X-Saw-Proxy-Auth") != "" {
		t.Fatal("proxy credentials must never reach the origin")
	}
}

func TestMissingCredentialsGets407(t *testing.T) {
	proxy := httptest.NewServer(&Proxy{Credentials: "svc:s3cret", Allow: func(string) bool { return true }})
	defer proxy.Close()
	pu, _ := url.Parse(proxy.URL)
	client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(pu)}}
	resp, err := client.Get("http://198.51.100.1/")
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()
	if resp.StatusCode != http.StatusProxyAuthRequired || resp.Header.Get("Proxy-Authenticate") == "" {
		t.Fatalf("want 407 with Proxy-Authenticate, got %d", resp.StatusCode)
	}
}

func TestOriginFormRequestIsRejected(t *testing.T) {
	proxy := httptest.NewServer(&Proxy{Allow: func(string) bool { return true }})
	defer proxy.Close()
	resp, err := http.Get(proxy.URL + "/not-absolute")
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()
	if resp.StatusCode != http.StatusBadRequest {
		t.Fatalf("want 400, got %d", resp.StatusCode)
	}
}

The Go angle ​

  • httputil.ReverseProxy has two ways to rewrite a request. Director is deprecated; Rewrite receives a ProxyRequest with In (read only) and Out, and the library removes hop-by-hop headers and the Forwarded, X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto headers from Out before calling it. That default is the safe one: nothing the client sent survives unless you copy it, as rproxy does only for trusted peers.
  • ProxyRequest.SetXForwarded() writes X-Forwarded-For (appending the client IP to an existing value), X-Forwarded-Host and X-Forwarded-Proto; SetURL rewrites the target and the Host header. Copy In.Header["X-Forwarded-For"] into Out first if and only if the peer is a trusted proxy.
  • The proxy and its transport are separate objects. Put policy (retry, ejection, timeouts) in a RoundTripper and keep ReverseProxy for header and error mapping. ErrorHandler is where 502 and 504 are decided; the default is 502 for everything, so timeouts need explicit handling.
  • A proxy needs a tuned http.Transport: MaxIdleConnsPerHost (default 2), IdleConnTimeout, ResponseHeaderTimeout, a net.Dialer timeout. Do not use http.DefaultTransport in a proxy.
  • Streaming: FlushInterval: -1 flushes after every write; the documentation says FlushInterval is ignored for responses the proxy recognises as streaming and for unknown content length, which are flushed immediately.
  • Upgrades: ReverseProxy detects Connection: Upgrade and handles 101 Switching Protocols by hijacking both connections. The test shows an echo through it.
  • A forward proxy in Go needs http.Hijacker for CONNECT and CloseWrite on *net.TCPConn for half-close. HTTP/2 servers cannot hijack; serve the proxy listener with HTTP/1.1.
  • Behind a proxy, a Go server reads the client address with its own clientip.FromRequest; r.RemoteAddr is the proxy. http.Server has no built-in trusted-proxy logic.
  • Graceful shutdown: srv.Shutdown(ctx) stops accepting and waits for active requests; hijacked connections (WebSocket, CONNECT tunnels) are not tracked by Shutdown, so close them yourself.

Laravel ​

Example: trusted proxies, URL generation behind TLS termination, Octane behind NGINX ​

The bootstrap file above trusts only the proxy ranges from TRUSTED_PROXIES, trusts only the headers the edge really sets, and restricts the Host header with trustHosts. The controller and the feature test below show and prove the behaviour. The Octane NGINX configuration from the Laravel documentation is the reference for a long-running application server behind a reverse proxy: it serves static files from NGINX, proxies the rest to the Octane server on port 8000, sends Host, X-Forwarded-For, Upgrade and Connection headers with an $connection_upgrade map.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class WhoAmIController extends Controller
{
    /**
     * Shows what the application believes about the request after TrustProxies ran.
     * Behind a trusted proxy these values come from X-Forwarded-*; from anyone else they
     * come from the TCP connection and the headers are ignored.
     */
    public function __invoke(Request $request): JsonResponse
    {
        return response()->json([
            'ip' => $request->ip(),                 // the client address after proxy resolution
            'ips' => $request->ips(),               // every client address Laravel found in the forwarded chain (order: see the Laravel docs)
            'secure' => $request->isSecure(),       // true when X-Forwarded-Proto: https is trusted
            'host' => $request->getHost(),          // from X-Forwarded-Host when trusted
            'root' => $request->root(),             // base of generated absolute URLs
            'login_url' => route('login'),          // https://app.example.com/login behind TLS termination
            'server_remote_addr' => $request->server('REMOTE_ADDR'), // the proxy itself
        ]);
    }
}
php
<?php

namespace Tests\Feature;

use Tests\TestCase;

class TrustProxiesTest extends TestCase
{
    public function test_trusted_proxy_headers_are_applied(): void
    {
        // REMOTE_ADDR is inside TRUSTED_PROXIES, so X-Forwarded-* is believed.
        $response = $this->withServerVariables(['REMOTE_ADDR' => '10.0.0.5'])
            ->withHeaders([
                'X-Forwarded-For' => '198.51.100.7',
                'X-Forwarded-Proto' => 'https',
                'X-Forwarded-Host' => 'app.example.com',
            ])
            ->getJson('/whoami');

        $response->assertOk()->assertJson([
            'ip' => '198.51.100.7',
            'secure' => true,
            'host' => 'app.example.com',
        ]);
    }

    public function test_untrusted_peer_cannot_forge_the_client_address(): void
    {
        // A direct client (outside TRUSTED_PROXIES) sends a forged header.
        $response = $this->withServerVariables(['REMOTE_ADDR' => '203.0.113.50'])
            ->withHeaders(['X-Forwarded-For' => '10.1.2.3', 'X-Forwarded-Proto' => 'https'])
            ->getJson('/whoami');

        $response->assertOk()->assertJson([
            'ip' => '203.0.113.50',
            'secure' => false,
        ]);
    }
}
php
<?php

namespace App\Services;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

/**
 * Outbound calls from the application go through the company forward proxy.
 * "proxy" and "no" are Guzzle request options, passed with withOptions().
 */
class EgressClient
{
    public function make(): PendingRequest
    {
        return Http::withOptions([
            'proxy' => [
                'http' => (string) config('services.egress.http'),    // e.g. http://svc:secret@egress.internal.example:3128
                'https' => (string) config('services.egress.https'),  // HTTPS is tunnelled with CONNECT
                'no' => ['.internal.example', 'localhost', '127.0.0.1'], // never proxy internal destinations
            ],
        ])->connectTimeout(3)->timeout(10)->retry(2, 200, throw: false);
    }
}

The Laravel angle ​

  • Illuminate\Http\Middleware\TrustProxies is configured in bootstrap/app.php with $middleware->trustProxies(at: ..., headers: ...). The Laravel documentation says the symptom of not doing so is that the url helper does not generate HTTPS links behind a load balancer that terminates TLS.
  • at: '*' trusts every peer. The documentation offers it for cloud load balancers whose addresses are unknown; only use it when the application cannot be reached except through the balancer (private subnet, security group that allows only the balancer).
  • The headers argument picks which headers are believed: Request::HEADER_X_FORWARDED_FOR | HEADER_X_FORWARDED_HOST | HEADER_X_FORWARDED_PORT | HEADER_X_FORWARDED_PROTO, HEADER_X_FORWARDED_AWS_ELB for AWS Elastic Load Balancing, HEADER_FORWARDED for a balancer that sends the RFC 7239 header.
  • After TrustProxies, $request->ip(), $request->ips(), $request->isSecure(), $request->getHost(), url(), route() and signed URL validation use the forwarded values. Signed URLs fail validation if the host or scheme differ between signing and verification, a common symptom of a missing proxy trust.
  • trustHosts(at: [...]) (the TrustHosts middleware) rejects requests whose Host header is not on the list; it matters because the Host header (or X-Forwarded-Host when trusted) builds absolute URLs, password reset links included.
  • Rate limiters key by $request->ip(). Behind an untrusted proxy setup every user shares the balancer's address and a limit of 60 per minute locks everybody out at once; see the Laravel rate limiting in Rate Limiting Algorithms.
  • Outbound: Http::withOptions([...]) passes Guzzle request options; the Guzzle proxy option takes a string or an array per scheme with a no list, and CONNECT is used for HTTPS targets.
  • Octane: FrankenPHP, RoadRunner or Swoole serve the app; Laravel's documentation says to serve production Octane behind a traditional web server, which will "serve your static assets such as images and stylesheets, as well as manage your SSL certificate termination". Since the app sees the proxy as peer, TrustProxies applies exactly as with FPM.
  • PHP-FPM behind NGINX is a reverse proxy relationship too, using FastCGI (fastcgi_pass) instead of proxy_pass; the same timeouts exist as fastcgi_read_timeout.
sql
-- Request log with both addresses, to catch a misconfigured trust list
CREATE TABLE http_access (
  at          timestamptz NOT NULL DEFAULT now(),
  peer_addr   inet        NOT NULL,      -- TCP peer (the proxy) = REMOTE_ADDR
  client_addr inet        NOT NULL,      -- address the app resolved after TrustProxies
  xff         text,                      -- raw X-Forwarded-For for forensics
  status      smallint    NOT NULL,
  path        text        NOT NULL
);

-- If client_addr equals peer_addr for most rows behind a proxy, the trust list is wrong.
SELECT peer_addr, count(*) AS requests,
       count(*) FILTER (WHERE client_addr = peer_addr) AS unresolved
FROM http_access
WHERE at > now() - interval '1 hour'
GROUP BY peer_addr
HAVING count(*) FILTER (WHERE client_addr = peer_addr) > 0.9 * count(*);

Solving the classic problems ​

Every user appears to come from the load balancer ​

CauseFixAdvantageCost or limit
App reads REMOTE_ADDRTrust the proxy and read the forwarded address (TrustProxies, set_real_ip_from)Correct IPs in logs, limits, geoRequires an accurate trusted list
L4 balancer hides the clientPROXY protocol v2 to the next tierWorks for any protocolBoth ends must agree
CDN in frontTrust the CDN ranges; read CF-Connecting-IP or XFF behind itReal visitor IPMaintain the CDN range list

Redirect loop or http links behind HTTPS ​

CauseFixAdvantageCost or limit
App thinks the request is plain HTTPSend X-Forwarded-Proto: https and trust itAbsolute URLs and redirects correctTrust list needed
"HTTPS redirect" at both proxy and appRedirect only at the outermost proxyNo loopOne owner of the rule
Cookie Secure flag not setFix the scheme first, then secure cookies workSession safetyNone

502 for a few hundred milliseconds on every deploy ​

CauseFixAdvantageCost or limit
App stopped before the proxy stopped sendingReadiness fails first, delay (preStop sleep), then SIGTERM, drainZero failed requestsSlower deploys
Idle keepalive raceUpstream idle timeout longer than proxy pool lifetimeNo sporadic resetsTune both ends
Retry disabledproxy_next_upstream error timeout for idempotent requestsHides the blipPOST not retried

504 on long operations ​

CauseFixAdvantageCost or limit
Endpoint needs more than the proxy read timeoutMake it asynchronous: 202 plus status resourceScales, survives retriesClient code changes
Raising the timeout everywhereRaise on one location only, keep the global tightContainedStill ties up a worker
Retry after 504 duplicates the workIdempotency keySafeStorage for keys

WebSocket drops at 60 seconds ​

CauseFixAdvantageCost or limit
Proxy idle timeoutLonger proxy_read_timeout / timeout tunnel and application pingsStable connectionsIdle sockets hold memory
Upgrade headers droppedSet Upgrade and Connection explicitlyHandshake succeedsConfig per location
ALB idle timeoutHeartbeat shorter than the idle timeoutWorks without configTraffic overhead

Slow uploads exhaust workers ​

CauseFixAdvantageCost or limit
App reads the body from the client directlyproxy_request_buffering on, body timeoutsWorkers busy only when the body is completeDisk or memory for buffers
Huge filesDirect-to-object-storage upload with a presigned URLBypasses the app tierExtra flow

Server-side request forgery through a fetching feature ​

CauseFixAdvantageCost or limit
App fetches user-supplied URLsRoute through an egress proxy with an allow-list and a block on private rangesCentral enforcementProxy is a new dependency
DNS rebindingResolve once at the proxy and connect to that addressCloses the rebinding gapProxy must pin the IP

Choosing ​

SituationChooseExtra techniqueReason
Control or log outbound traffic from serversForward proxy (Squid or a managed gateway) with an allow-listNetwork rule that blocks direct egressAn app-level setting can be removed by an attacker
Public website or API on a few serversNGINX or Caddy as a reverse proxyTight timeouts, buffering, rate limitSimple, fast, well known
TCP service (database, MQTT, SMTP)L4 proxy (HAProxy mode tcp, NLB)PROXY protocol v2No HTTP to parse
Backend must own the TLS keyTLS passthrough at an L4 proxySNI routingKeys never leave the backend
Path or host routing, WAF, header logicL7 reverse proxy (NGINX, HAProxy, Envoy, ALB)Re-encrypt inside the VPCHTTP awareness
Containers with changing addressesTraefik, Envoy Gateway or a Kubernetes ingress controllerProvider based discoveryConfig follows the platform
Service-to-service mTLS and retriesSidecar mesh (Envoy under Istio or Linkerd)Outlier detectionUniform policy without code
Global traffic, DDoS, cachingCloudflare or another CDN in frontTrust only its ranges at the originAbsorbs attacks at the edge
Browsers must use the proxyPAC or MDM-pushed settingsDIRECT for internal rangesNo manual client setup
Legacy non-HTTP clientSOCKS5Auth and allow-listProtocol agnostic

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One Laravel application on one VM: NGINX terminates TLS on 443, serves static files, and passes dynamic requests to PHP-FPM. There is a reverse proxy even here, and it already does the job that matters: it absorbs slow clients, enforces a body limit and writes the access log. TrustProxies is not needed yet (NGINX uses FastCGI and sets REMOTE_ADDR from the socket). The first time a cloud load balancer or CDN is put in front, REMOTE_ADDR becomes the balancer and the trusted-proxy configuration becomes the first thing to get right.

Modular monolith: boundaries without the network ​

Several modules in one deployable, but traffic arrives on several hostnames and paths (app.example.com, api.example.com, /admin). The proxy routes by host and path to separate pools of the same codebase (public, API, admin), which lets admin be restricted by network and API be rate limited differently, without splitting the code. Egress becomes a decision: the payment module and the webhook module call out, and a forward proxy with an allow-list is the cheapest control to stop one module from reaching what only the other may.

Microservices: every arrow is a decision ​

 1  browser          -> Cloudflare           TLS, WAF, DDoS filtering; sets CF-Connecting-IP and X-Forwarded-For
 2  Cloudflare       -> AWS NLB              TCP 443, passthrough to the proxy fleet
 3  NLB              -> Envoy edge fleet     PROXY protocol v2 carries the Cloudflare address; Envoy terminates TLS
 4  Envoy edge       -> gateway              L7 routing, JWT check, rate limit by resolved client address
 5  gateway          -> orders sidecar       mTLS, retry policy, timeout 3 s
 6  orders sidecar   -> orders app           plain localhost, X-Request-Id propagated
 7  orders app       -> egress proxy         CONNECT api.carrier.example:443, allow-listed, logged

Seven hops, four different places that can mint or forward the client address. Each one needs a rule: who may set X-Forwarded-For, which header is authoritative at each tier, which timeout belongs to which hop (and they shrink inward), which tier retries. The common failure is a chain where each team trusts the previous tier's header without checking the previous tier is theirs. See Service Communication for budgets and Service Mesh & Sidecar for the east-west part.

Distributed data: replicas, caches, regions ​

Proxies appear in front of data too. A connection-pooling proxy (PgBouncer, ProxySQL) is an L7-ish proxy for the database wire protocol, covered in Connection Pooling; HAProxy in mode tcp fronting PostgreSQL replicas gives read/write splitting only if something decides which port is primary (see Replication, Read Replicas & Failover). A caching reverse proxy is a cache tier with the trade-offs in Caching: stale content, purge, cache keys that must include the variants (Accept-Encoding, language, cookies). Multi-region: a global proxy (Cloudflare, an anycast load balancer) steers by latency and health; see IP, DNS & GeoDNS. The client address is the first thing lost across regions, so carry it in the chain consistently.

Scaling path: 1x, 10x, 100x ​

LoadDesignWhat breaks firstFix
1x: hundreds of requests per secondOne NGINX in front of one app serverSingle point of failure; slow uploads hold workersRequest buffering, a second app server
10x: thousands of rpsTwo NGINX or an ALB in front of a pool; keepalive upstream; health checksEphemeral port exhaustion to upstreams, idle-timeout races, wrong client IPKeepalive pools, tuned timeouts, trusted proxies
100x: tens of thousands of rps and multi-regionCDN and anycast edge, L4 tier plus L7 fleet, PROXY protocol, outlier detection, rate limits at the edgeConfig sprawl, reload blast radius, certificate rotation, noisy neighboursDynamic config (xDS), progressive rollout, per-tenant limits, observability

Lab: forging an address, then fixing it, with tests ​

All steps run on one machine with the Go toolchain; the NGINX and Laravel steps are expected output, not run (marked below).

  1. Run the Go tests, which exercise the forged-header case, the retry case, 502, 504, upgrade and CONNECT:
$ cd docs/snippets/system-design/proxies-forward-reverse/go
$ go test -race -count=1 ./...
?       academy/proxies-forward-reverse/before      [no test files]
?       academy/proxies-forward-reverse/cmd/egress  [no test files]
ok      academy/proxies-forward-reverse/clientip    1.0s
ok      academy/proxies-forward-reverse/fproxy      1.0s
ok      academy/proxies-forward-reverse/rproxy      1.2s
  1. Expected, not run: reproduce the spoofing with the naive function. A client that sends X-Forwarded-For: 203.0.113.99 gets that value back from before.ClientIP; the clientip version returns the TCP peer. The test TestNaiveVersionIsSpoofable is exactly this experiment.
  2. Expected, not run: start two tiny upstreams (python3 -m http.server 8081 and 8082), point rproxy at them with Upstreams, stop one, and curl 20 times: every response is 200 because the dial error is retried on the other server and the dead one is ejected for EjectFor.
  3. Expected, not run: make an upstream sleep longer than ResponseHeaderTimeout and observe 504; stop all upstreams and observe 502.
  4. Expected, not run (NGINX): nginx -t && nginx -s reload with the reference config; curl -sI -H 'X-Forwarded-For: 203.0.113.99' https://app.example.com/whoami through the proxy shows ip equal to the real client address in the Laravel JSON when TRUSTED_PROXIES includes the proxy, and equal to the proxy address when it does not.
  5. Expected, not run (CONNECT): HTTPS_PROXY=http://svc:s3cret@127.0.0.1:3128 curl -v https://example.org against EGRESS_ALLOW=example.org:443 EGRESS_CREDENTIALS=svc:s3cret go run ./cmd/egress shows CONNECT example.org:443, HTTP/1.1 200 Connection Established, then a TLS handshake that the proxy cannot read; a destination not on the allow-list shows 403, a missing password shows 407.

Common misconceptions ​

BeliefReality
A proxy is a firewallA firewall filters packets by rules; a proxy terminates a connection and opens another. Combine them; neither replaces the other
X-Forwarded-For is the client IPIt is a list; only entries added by proxies you operate are reliable; the leftmost is the client's own claim
* in trusted proxies is fine because "we have a load balancer"Only if the app cannot be reached any other way; otherwise any caller can forge the address
A reverse proxy only does load balancingIt also terminates TLS, caches, compresses, limits, filters, authenticates and normalises headers
Forward proxies cannot see HTTPS at allThey see host and port with CONNECT, and everything if TLS interception with a trusted CA is used
504 means the application is downIt means the proxy stopped waiting; the application may be alive and still working
proxy_read_timeout limits the whole requestIt limits the gap between two reads from the upstream
Retrying on another server is always safeOnly for idempotent requests, or when no byte was delivered
HTTP/2 to the client means HTTP/2 to the appThe proxy usually speaks HTTP/1.1 upstream
Transparent proxy means no configuration or riskIt needs interception rules and, for HTTPS, a trusted CA; failures are hard to diagnose
PROXY protocol is just a header the server may use if presentThe listener must be configured to require it from known proxies only
A WebSocket needs no special proxy configUpgrade and Connection are hop-by-hop and must be passed explicitly, and idle timeouts apply

Cheat sheet ​

TopicWhat to remember
Forward vs reverseForward speaks for clients (egress control); reverse speaks for servers (front door)
GatewayRFC 9110: a gateway is a reverse proxy; a tunnel is a blind relay
CONNECTAuthority-form request, then 200 and blind byte copy; port-restrict it
L4 vs L7L4 moves bytes (passthrough, any protocol); L7 reads HTTP (routing, headers, caching)
TLSTerminate for L7 features; passthrough to keep the key at the backend; re-encrypt inside shared networks
X-Forwarded-ForComma list; read from the right through trusted hops; never the leftmost
Trusted proxiesBelieve forwarding headers only from listed peers; Laravel trustProxies(at:, headers:)
PROXY protocolOne header at the start of the TCP stream; accept only from known proxies; v2 is binary
Hop-by-hopConnection, Keep-Alive, Upgrade, TE, Trailer, Transfer-Encoding, Proxy-*: strip and reset per hop
502 vs 504502: invalid or no response; 504: no response in time
TimeoutsNGINX connect/send/read default 60 s; read and send are gaps, not totals
BufferingRequest buffering protects the app from slow clients; turn off for streaming
Keepalive upstreamHTTP/1.1, pooled connections, upstream idle timeout longer than the pool's
WebSocketPass Upgrade and Connection; lengthen the idle timeout; send pings
RetriesIdempotent and before any byte is delivered; never blindly on POST
ReloadTest the config, send HUP, old workers drain; restart drops connections

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What is the difference between a forward proxy and a reverse proxy, and who configures each? Must-know ​

Answer

Answer: A forward proxy is chosen by the client side (configuration, PAC, or interception) and speaks for clients toward many origins: egress control, caching, filtering. A reverse proxy is run by the server owner and reached through DNS; it speaks for servers toward many clients: TLS termination, routing, balancing. RFC 9110 calls the second a gateway.

2 — Why can a forward proxy not read an HTTPS URL path when the client uses CONNECT? Important ​

Answer

Answer: After the 200 response the proxy is a blind relay of TLS bytes (RFC 9110 section 9.3.6). It knows the host and port from the CONNECT target and sees volume and timing, but the path and headers are encrypted unless the proxy does TLS interception with a CA the client trusts.

3 — When is an L4 proxy the right choice over an L7 proxy? Must-know ​

Answer

Answer: For non-HTTP protocols, TLS passthrough where the backend must hold the key, extreme throughput, and as a first tier that spreads connections over several L7 proxies. The price is no routing by URL, no header changes and no per-request retries.

4 — An application behind NGINX logs the load balancer's address for every request. List the causes and the fix. Important ​

Answer

Answer: The application reads the TCP peer, which is the proxy. Fix: have the proxy set X-Forwarded-For (and Proto/Host), and configure the application to trust that proxy's address range (Laravel trustProxies(at: ...), NGINX set_real_ip_from), reading the address from the right through trusted hops. For L4 balancers use the PROXY protocol.

5 — Why is trusting * in trustProxies dangerous, and when is it acceptable? Must-know ​

Answer

Answer: Any caller who can reach the application directly can forge X-Forwarded-For, Proto and Host. It is acceptable only when the network guarantees every request arrives through your balancer (private subnet, security group allowing only the balancer).

6 — What does proxy_read_timeout 60s measure, and why can a request run for ten minutes without tripping it? Important ​

Answer

Answer: It measures the time between two successive read operations from the upstream, not the whole response. A server that sends data at least every 60 seconds keeps the connection alive indefinitely.

7 — Distinguish a 502 from a 504 and say which is safe to retry for a POST. Must-know ​

Answer

Answer: 502: the proxy got an invalid response or could not connect or the connection was reset. 504: the proxy gave up waiting. A POST should not be blindly retried after either, because the upstream may have performed the work; retry only with an idempotency key, or when the connection never opened.

8 — Why does a WebSocket fail through NGINX without extra configuration? Must-know ​

Answer

Answer: Upgrade and Connection are hop-by-hop headers and are removed. They must be set explicitly with proxy_set_header Upgrade $http_upgrade and proxy_set_header Connection "upgrade" (on older builds with HTTP/1.1 upstream), and the read timeout must be long enough for idle connections.

9 — What problem does the PROXY protocol solve and what is the main rule when enabling it? Important ​

Answer

Answer: It carries the original client and destination addresses across an L4 proxy that cannot add HTTP headers. The receiver must be configured to require it, only from trusted proxies; otherwise a client could send its own header and spoof an address.

10 — How do you deploy without dropping requests behind a proxy? Must-know ​

Answer

Answer: Fail readiness first so the proxy stops sending new requests, wait for the health check to eject the instance, drain in-flight requests, then stop it. For the proxy itself, test the config and reload (HUP) so old workers finish their requests.

Glossary ​

TermDefinition
Forward proxyIntermediary chosen by the client that forwards requests to origins and applies policy
Egress proxyA forward proxy used to control outbound traffic from servers
Reverse proxyIntermediary that acts as the origin for clients and forwards to backend servers; RFC 9110 calls it a gateway
GatewayRFC 9110 term for a reverse proxy
TunnelA blind relay between two connections, created by CONNECT
Explicit proxyA proxy the client is configured to use
Transparent proxyA proxy the network steers traffic into without client configuration
PACProxy auto-config: a JavaScript FindProxyForURL function that picks a proxy per URL
HTTP CONNECTMethod that asks a proxy to open a TCP tunnel to host:port
SOCKS5Protocol (RFC 1928) for relaying arbitrary TCP and UDP through a proxy
TLS terminationThe proxy completes the TLS handshake and decrypts traffic
TLS passthroughThe proxy relays encrypted bytes; the backend holds the certificate
Re-encryptionTerminate TLS at the proxy, then open a new TLS connection to the upstream
L4 proxyProxy that relays TCP or UDP without parsing application protocols
L7 proxyProxy that parses and acts on application messages such as HTTP
UpstreamA backend server or pool a proxy forwards to (NGINX term)
X-Forwarded-ForDe facto header listing client and proxy addresses, appended per hop
X-Forwarded-ProtoDe facto header carrying the client-facing scheme
ForwardedRFC 7239 standard header with for, by, host and proto
X-Real-IPSingle-address header set by one proxy, by convention
Trusted proxiesThe list of peers whose forwarding headers an application believes
TrustProxiesLaravel middleware that applies trusted-proxy headers to the request
PROXY protocolHAProxy protocol that prefixes a TCP connection with the original addresses
Hop-by-hop headersHeaders that apply to one connection and must not be forwarded
ViaHeader recording the intermediaries a message passed through
502 Bad GatewayProxy received an invalid response or could not reach the upstream
504 Gateway TimeoutProxy did not get a timely response from the upstream
proxy_read_timeoutNGINX timer for the gap between two reads from the upstream
Request bufferingReading the whole request body at the proxy before contacting the upstream
Response bufferingReceiving the upstream response at the proxy before delivering it to the client
Keepalive upstreamReusing idle connections from the proxy to the upstream
WebSocket proxyingPassing Upgrade and Connection so a connection can switch protocols through the proxy
UpgradeHeader requesting a protocol switch, answered by 101
Health checkProbe or failure counting that decides whether an upstream receives traffic
Graceful reloadApplying new configuration while old workers finish their requests
WAFWeb application firewall: rules that block attack patterns in HTTP requests
SidecarA proxy deployed beside each service instance
API gatewayEdge reverse proxy with API features such as authentication and quotas
NGINXEvent-driven web server and reverse proxy
HAProxyL4 and L7 proxy and load balancer
EnvoyL3/L4 and L7 proxy used as a mesh data plane and gateway
TraefikDynamic reverse proxy for container platforms
CaddyReverse proxy and web server with automatic HTTPS
SquidCaching and filtering forward proxy
CloudflareGlobal reverse proxy and CDN service
ALBAWS Application Load Balancer, a managed L7 balancer

References ​

Built by Morteza Negahi