One middleman, two connections
A proxy is a program that makes connections on someone else's behalf. The most important thing to understand: there is no single connection "through" a proxy. There are two separate connections, and the proxy copies data between them.
Wide by design - scroll it sideways.
Almost everything in this chapter follows from this. The server sees the proxy's address, not the client's (section 9). Either connection can time out on its own (section 10). If one side fails, the proxy has to invent an error for the other side: that is where 502 and 504 come from (section 11).
Forward proxy: acting for the clients
A forward proxy sits on the clients' side. The clients know about it and are configured to use it; the websites just see the proxy.
Same kind of program, opposite sides. A forward proxy hides the clients from the servers; a reverse proxy hides the servers from the clients.
Wide by design - scroll it sideways.
| Filtering and logging | Offices and schools block categories of sites and keep a record of who went where |
| Egress control | Servers may reach only an allowlist (for example, only the payment provider). Cloud NAT gives a fixed IP; a proxy also controls which names can be reached. |
| Caching | One download of a big update, shared by many machines (CDNs and HTTP caching are a separate topic for later) |
| Privacy | Sites see the proxy's IP, not yours. A VPN does the same at the IP level, for all traffic. |
How HTTPS goes through a forward proxy. The proxy cannot read encrypted traffic, so the client asks it to open a plain tunnel with the CONNECT method, then does TLS straight to the site through it:
The proxy sees only the name and port it was asked to connect to, and how much data flows. Some companies do TLS inspection: the proxy decrypts everything, which only works because the company installs its own root CA on every work laptop (chapter 25). That is also why some tools fail with certificate errors on company networks.
Reverse proxy: acting for the servers
A reverse proxy sits on the servers' side. Clients think it is the server; they never know what is behind it. It is the single front door, and it takes jobs off the application:
| # | Job | What it means for kade-api | Chapter |
|---|---|---|---|
| 1 | TLS termination | Certificates and handshakes live in one place; Node speaks plain HTTP | 25 |
| 2 | Routing | By host or path: /api/* to kade-api, everything else to the frontend, so no CORS is needed | 28 |
| 3 | Load balancing | Spread requests over several backends and skip broken ones | section 4 |
| 4 | Buffering slow clients | A shopper on a weak 3G link uploads slowly; the proxy collects the whole request, then hands it to Node in one go, so Node is not tied up | 19 |
| 5 | Protocol translation | HTTP/3 or HTTP/2 outside, HTTP/1.1 inside | 24 |
| 6 | Protection | Rate limits, a WAF (Cloud Armor on GCP), absorbing SYN floods | 16 |
| 7 | Compression, static files, caching | gzip/brotli responses; serve images without touching Node | later topic |
| 8 | Hiding the backends | The VMs need no public IP at all | 10 |
The classic self-managed version is nginx on the same VM as Node. A minimal config shows several of these jobs:
server {
listen 443 ssl;
server_name api.kade.lk;
ssl_certificate /etc/letsencrypt/live/api.kade.lk/fullchain.pem; # TLS ends here
ssl_certificate_key /etc/letsencrypt/live/api.kade.lk/privkey.pem;
location / {
proxy_pass http://127.0.0.1:3000; # Node listens on localhost only (chapter 31)
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # section 9
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 60s; # section 10
proxy_http_version 1.1; # needed for WebSockets (chapter 26) …
proxy_set_header Upgrade $http_upgrade; # … and these two headers
proxy_set_header Connection "upgrade";
}
}
| # | Forward proxy | Reverse proxy | |
|---|---|---|---|
| 1 | Sits with | the clients | the servers |
| 2 | Who configures it | the client (settings, env vars) | nobody on the client: DNS simply points to it |
| 3 | Hides | the clients | the servers |
| 4 | HTTPS | usually a blind CONNECT tunnel | usually terminates TLS and reads everything |
| 5 | Examples | office web filter, Squid, SSH -D | nginx, Envoy, HAProxy, Cloudflare, GCP load balancers |
Load balancers: Kadé gets one
A load balancer is a reverse proxy whose main job is spreading traffic over several backends. It gives three things one VM cannot: capacity (add VMs as orders grow), availability (one VM can crash or reboot), and safe deploys (update one VM at a time).
This is the change chapter 0 promised. Kadé's API moves behind a GCP external Application Load Balancer:
Only DNS changed for shoppers (chapter 22): api.kade.lk now points to 34.120.88.10. That IP is anycast (chapter 12): Google announces it from many edge locations, and each shopper connects to the nearest one. The front end talks plain HTTP to port 8080 inside the VPC. Both requests and health checks reach the VMs from Google's ranges 35.191.0.0/16 and 130.211.0.0/22, so the VPC firewall must allow those to port 8080.
Wide by design - scroll it sideways.
Layer 4 vs layer 7
Chapter 11 introduced these names. The difference is how much of the packet the load balancer reads:
| # | Layer 4 | Layer 7 | |
|---|---|---|---|
| 1 | Decides using | IP addresses and ports | anything in the HTTP request: path, host, headers, cookies |
| 2 | Balances | whole connections | individual requests |
| 3 | Protocols | anything on TCP/UDP: databases, MQTT, games, DNS | HTTP(S), HTTP/2, HTTP/3, gRPC, WebSockets |
| 4 | TLS | passed through (the backend holds the certificate), or simple termination | terminated; the LB holds the certificate |
| 5 | Can do | very fast, very cheap per packet | path routing, redirects, header changes, retries, WAF, cookies for stickiness |
| 6 | Client IP at the backend | kept (passthrough), or via PROXY protocol | via X-Forwarded-For (section 9) |
| # | GCP load balancer | Layer | Proxy? | Typical use |
|---|---|---|---|---|
| 1 | External Application LB | 7 | yes | Public websites and APIs: Kadé's choice |
| 2 | Internal Application LB | 7 | yes | HTTP between internal services |
| 3 | External proxy Network LB | 4 | yes (TCP proxy) | Non-HTTP TCP services from many regions |
| 4 | Passthrough Network LB (external / internal) | 4 | no: packets pass through with the client's IP | UDP, games, anything that must see the real client IP or do its own TLS |
Choosing a backend
| Round robin | 1, 2, 3, 1, 2, 3 … Simple and fair when requests are similar. GCP's default. |
| Weighted | A bigger VM gets a bigger share; also used to send 5% to a new version (a "canary") |
| Least connections / least requests | Pick the backend with the fewest requests in progress. Better when some requests are slow (reports, exports). |
| Hash | Hash of client IP, a header or a cookie picks the backend, so the same client lands on the same place (section 8). "Consistent hashing" limits reshuffling when a backend is added or removed. |
Try it. Four shoppers take turns sending requests; Shopper A's requests are slow reports. Shoppers C and D are on the same mobile carrier, so they share one public IP through carrier NAT (chapter 10). Crash a VM and watch the health checker catch it:
in progress 0 · served 0
in progress 0 · served 0
in progress 0 · served 0
- Send some requests. Then try: Least requests vs Round robin with Shopper A’s slow reports; crash a VM; sticky by client IP for Shoppers C and D.
Each request here is 1 second of time. Health checks run every 2 s and need 2 failures or 2 successes (real GCP defaults: every 5 s, 2 and 2). Squares are requests in progress; plum ones are slow reports.
Health checks and draining
A load balancer must stop sending traffic to a broken backend. It finds out in two ways:
| Active health checks | It sends a probe, e.g. GET /healthz, to every backend on a schedule. GCP defaults: every 5 s, 5 s timeout, 2 failures = unhealthy, 2 successes = healthy again. |
| Passive (outlier detection) | It watches real traffic and pulls out a backend that keeps returning errors or refusing connections |
What should /healthz check? Two different questions are easy to mix up:
| # | Question | Should include | Careful with |
|---|---|---|---|
| 1 | "Is this process alive?" (liveness) | Only the process itself: answer 200 quickly | - |
| 2 | "Should this VM get traffic right now?" (readiness) | Started up fully, not shutting down, not overloaded | Shared dependencies. If /healthz fails whenever kade-db is slow, every backend fails at once, and the load balancer has nothing left to send traffic to. A database hiccup becomes a total outage, even for endpoints that never touch the database. |
Draining. During a deploy, killing a VM cuts off requests in progress. The clean way: tell the load balancer first, let in-flight requests finish, then stop:
let shuttingDown = false;
app.get('/healthz', (req, res) => res.sendStatus(shuttingDown ? 503 : 200));
process.on('SIGTERM', () => {
shuttingDown = true; // 1. health checks now fail → LB stops sending new requests
setTimeout(() => server.close(), 15000); // 2. wait longer than 2 failed checks, then stop accepting
}); // 3. server.close() lets in-flight requests finish
GCP backend services also have a connection draining timeout: when a VM is removed from the group, the load balancer stops sending it new requests but lets existing ones finish for that long.
Sticky sessions
Sticky sessions (session affinity) send the same client to the same backend every time. They are needed when a backend keeps something in memory for a client: a login session stored in Node's memory, an in-progress upload, or a WebSocket chat room (chapter 26).
| # | How | Works by | Problem |
|---|---|---|---|
| 1 | Cookie | The LB sets a cookie naming the backend (GCP's generated cookie is called GCLB) | Needs cookies; only for HTTP (layer 7) |
| 2 | Client IP | A hash of the source IP | Everyone behind one carrier NAT or office lands on the same VM; a phone moving from WiFi to 4G changes IP and "loses" its backend |
| 3 | Header | A hash of a header, e.g. a user ID | The client must send it |
Who is the client? X-Forwarded-For and friends
Because of the two connections (section 1), kade-api's socket sees the load balancer's address, never the shopper's. Without extra help, every request seems to come from 35.191.x.x. That breaks:
| Rate limiting per IP | All shoppers look like one IP: one busy user gets everyone blocked, or the limit never triggers |
| Logs and fraud checks | Every order was "placed from Google". The same problem NAT caused in chapter 10. |
| HTTPS detection | The LB talks plain HTTP to Node, so Node thinks every request is http. An app rule "redirect http to https" then redirects forever (the redirect comes back through the LB as http again), and Secure cookies are not set. |
| Building URLs | Links in emails and redirects use the internal host and port |
Proxies fix this by adding request headers that describe the original connection:
| # | Header | Kadé example | Meaning |
|---|---|---|---|
| 1 | X-Forwarded-For | 203.0.113.45, 34.120.88.10 | The client's IP. Each proxy appends the address it received the connection from, so the list grows left to right. |
| 2 | X-Forwarded-Proto | https | The scheme the client used on the first connection |
| 3 | X-Forwarded-Host | api.kade.lk | The original Host, when a proxy changes it |
| 4 | Forwarded | for=203.0.113.45;proto=https | The official standard version of all three; less widely used |
| 5 | Via | 1.1 google | Which proxies the request passed through |
In Express, the trust proxy setting says how many hops to skip. It then fills in req.ip, req.protocol and req.secure correctly. Try different paths and settings:
| Hop | X-Forwarded-For after this hop | Note |
|---|---|---|
| Laptop sends the request | (none) | from 192.168.1.23 |
| Home router (NAT) | (none) | rewrites the IP only; it cannot touch HTTP (it is encrypted) |
| GCP load balancer | 203.0.113.45, 34.120.88.10 | saw the connection come from 203.0.113.45; appends it, then its own IP |
| Node receives | 203.0.113.45, 34.120.88.10 | socket peer: 35.191.12.34 |
- Hops Express reads
- 0: 35.191.12.34 · 1: 34.120.88.10 · 2: 203.0.113.45
- req.ip
- 35.191.12.34
- req.protocol
- http · Node only sees its own plain-HTTP socket: https redirects loop, Secure cookies are not set
35.191.12.34 is a proxy (the Google front end), not the client. Every request looks like it came from here.
Express lists the socket peer first (hop 0), then X-Forwarded-For from right to left. trust proxy = N picks hop N. For this path the right value is 2: the number of entries your own proxies add. true takes the leftmost entry, which the client controls.
Timeouts along the chain
Every hop has its own timers, because every connection is separate. Two different kinds matter:
| # | Hop | Request timeout (how long to wait for an answer) | Idle timeout (how long an unused connection is kept) |
|---|---|---|---|
| 1 | Kadé app / browser | whatever the code sets (fetch has none by default) | browser's own |
| 2 | GCP load balancer | backend service timeout: 30 s by default. Also the maximum life of a WebSocket (chapter 26). | ~10 minutes to clients and to backends (chapter 21) |
| 3 | Node | requestTimeout 300 s, headersTimeout 60 s | keepAliveTimeout: 5 s by default; must be longer than the LB's (set ~620 s) |
| 4 | PostgreSQL | statement_timeout: none by default | pool idle timeout (chapter 21) |
| Rule 1 · request timeouts | Inner shorter than outer. The database should give up before Node, and Node before the load balancer. Then the app returns its own clear error, instead of the load balancer returning a 504 while the work keeps running. |
| Rule 2 · idle timeouts | Inner longer than outer. The backend must keep an idle connection open longer than the load balancer does, or the LB reuses a connection Node just closed: random 502s (chapter 21). |
A timeout does not stop the work behind it. When the load balancer gives up after 30 s, Node and the database keep going. If the shopper then taps "Place order" again, the order may be created twice: that is exactly what idempotency keys prevent (chapter 24). Drag the slider to see who gives up first:
| Layer | Timeout | This request |
|---|---|---|
| Kadé app gives up | 20 s | gives up first |
| GCP load balancer (backend service timeout) | 30 s | would give up |
| Node requestTimeout | 300 s | waits |
| PostgreSQL statement_timeout | none | waits |
The app gives up at 20 s and shows "something went wrong". The load balancer, Node and the database keep going. If this was "place order", the order may still be created, and a retry may create a second one: use an idempotency key (chapter 24).
Still running after the shopper got an answer: Node, PostgreSQL.
Reading 502, 503 and 504
Chapter 24 noted that these codes usually come from the box in front of your app, not from your code. With a load balancer in place, here is how to read them:
| # | Status | What the LB is saying | Example GCP log detail | Usual causes at Kadé | Fix |
|---|---|---|---|---|---|
| 1 | 502 Bad Gateway | "I reached a backend, but got a broken reply or none" | backend_connection_closed_before_data_sent_to_client | Node's keep-alive shorter than the LB's (the race); Node crashed mid-request | keepAliveTimeout ~620 s; check for crashes |
| 2 | 502 | "I could not connect to the backend" | failed_to_connect_to_backend | Node not listening on 8080, or listening on 127.0.0.1 only (chapter 31); firewall | Bind 0.0.0.0:8080; allow the LB ranges |
| 3 | 502 / 503 | "There is no healthy backend to pick" | failed_to_pick_backend | Health checks failing on every VM: often the firewall blocks 35.191.0.0/16, or /healthz depends on the database | Check get-health; fix the firewall or the health endpoint |
| 4 | 504 Gateway Timeout (or 502) | "The backend took too long" | backend_timeout | A slow endpoint over 30 s, e.g. a big export | Speed it up, make it a background job, or raise that route's timeout |
| 5 | 503 from your app | Your code says "not now" | response_sent_by_backend | Draining, overloaded, or a deliberate maintenance response | Expected during deploys |
statusDetails field always says exactly what happened. Quick check from outside: an error page generated by the load balancer has Google's HTML body and none of your app's own headers.Where does TLS end?
Chapter 25 ended by asking where TLS should stop. With a load balancer there are four common choices:
| # | Option | Shopper → LB | LB → kade-api | Trade-off |
|---|---|---|---|---|
| 1 | Terminate at the LB | HTTPS | HTTP inside the VPC | Simplest; the LB can do everything in section 3. Google also encrypts traffic between its front ends and VMs at the network level. Kadé's choice. |
| 2 | Terminate and re-encrypt | HTTPS | HTTPS (backend has its own certificate) | Encrypted on every hop, for strict rules like card data; more certificates to manage |
| 3 | Passthrough | One TLS session from the shopper straight to the VM (layer 4 LB) | The LB sees nothing: no routing by path, no X-Forwarded-For, no WAF | |
| 4 | Mutual TLS at the LB | HTTPS + a client certificate | HTTP, plus headers saying who the client was | For machine clients such as partners (chapter 25) |
Common mistakes
| # | Symptom | Cause | Fix |
|---|---|---|---|
| 1 | All backends unhealthy right after setup | Firewall does not allow 35.191.0.0/16 and 130.211.0.0/22 | Add an ingress rule for those ranges to port 8080 |
| 2 | A few random 502s per day | Keep-alive race (chapter 21) | Node keepAliveTimeout longer than the LB's idle timeout |
| 3 | Every request logged from 35.191.x.x; rate limiter blocks everyone | trust proxy not set | Set it to the exact number of proxies |
| 4 | "Too many redirects" after adding the LB | App thinks requests are http | trust proxy, so req.secure reads X-Forwarded-Proto; or let the LB do the http → https redirect |
| 5 | WebSockets drop every 30 seconds | GCP's backend service timeout caps WebSocket life | Raise it for the WebSocket backend; reconnect with backoff anyway (chapter 26) |
| 6 | Exports fail with 504, but the file still gets generated | Request longer than the LB timeout; work continues | Background job + "we'll email you the file" |
| 7 | One VM hot, the other idle | Client-IP stickiness behind carrier NAT, or HTTP/2 through a layer 4 LB | Cookie affinity or none; layer 7 balancing |
| 8 | Errors on every deploy | VMs stopped without draining | Fail readiness first, wait, then close (section 7) |
Summary
| # | Idea | In one line | New terms |
|---|---|---|---|
| 1 | Proxy | Two separate connections with a program copying between them | proxy |
| 2 | Forward proxy | Acts for clients: filtering, egress control; HTTPS via CONNECT tunnels | forward proxy, CONNECT, TLS inspection, PAC |
| 3 | Reverse proxy | Acts for servers: TLS, routing, buffering, protection, one front door | reverse proxy |
| 4 | Load balancer | Reverse proxy spreading traffic over backends; Kadé now uses 34.120.88.10 | backend, instance group |
| 5 | L4 vs L7 | Ports and IPs vs full HTTP; connections vs requests | passthrough |
| 6 | Algorithms | Round robin, weighted, least requests, hashing | canary, consistent hashing |
| 7 | Health | Probes and outlier detection; readiness vs liveness; draining on deploy | health check, draining |
| 8 | Stickiness | Cookie, IP or header affinity; prefer stateless backends | session affinity |
| 9 | X-Forwarded-* | Real client IP and scheme; trust only your own proxies' entries | X-Forwarded-For/Proto, PROXY protocol |
| 10 | Timeouts | Request timeouts shrink inward; idle timeouts grow inward; work continues after a timeout | backend service timeout |
| 11-12 | 5xx and TLS | 502 broken reply, 503 nothing available, 504 too slow; choose where TLS ends | statusDetails |
Try it yourself
Headers added by a Google front end
- What to look for:
server: gws,alt-svc: h3=…; sites behind a GCP LB also showvia: 1.1 google. - From section: 4. Load balancers: Kadé gets one
curl -sI https://www.google.com | grep -i -E 'via|alt-svc|server'How a proxy appends to X-Forwarded-For
- What to look for: Your fake 1.2.3.4 first, then your real IP added by their load balancer.
- From section: 9. Who is the client? X-Forwarded-For and friends
curl -s -H 'X-Forwarded-For: 1.2.3.4' https://httpbin.org/headersA CONNECT tunnel
- What to look for:
CONNECT example.com:443, then200 Connection established, then TLS. - Runs on: if you have a proxy
- From section: 2. Forward proxy: acting for the clients
curl -v -x http://PROXY:3128 https://example.comProxy settings your tools will use
- What to look for: HTTP_PROXY / HTTPS_PROXY / NO_PROXY.
- From section: 2. Forward proxy: acting for the clients
env | grep -i proxyWhat the LB thinks of each VM
- What to look for:
healthState: HEALTHYfor every instance. - From section: 7. Health checks and draining
gcloud compute backend-services get-health kade-api-backend --globalRecent 5xx and why
- What to look for: The statusDetails names from section 11.
- From section: 11. Reading 502, 503 and 504
gcloud logging read 'resource.type="http_load_balancer" AND httpRequest.status>=500' --limit 10 --format='value(httpRequest.status,jsonPayload.statusDetails)'Node's default timeouts
- What to look for:
5000 60000 300000(ms). - From section: 10. Timeouts along the chain
node -e "const s=require('http').createServer();console.log(s.keepAliveTimeout,s.headersTimeout,s.requestTimeout)"