Chapters

Proxies, reverse proxies & load balancers

Since chapter 1, the laptop talked straight to kade-api. Real services almost never work like that: something sits in the middle. This chapter explains those middle boxes, gives Kadé its load balancer, and brings together pieces from earlier chapters: TLS termination (25), 502s from keep-alive races (21), 5xx codes (24), WebSocket timeouts (26) and NAT's hidden clients (10).

Putting it together · chapter 33 of 34 · 16 min read

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.

Laptop203.0.113.45 (after NAT)Proxycopies data betweenits two connectionskade-api10.10.1.11connection 1own handshake, own TLS,own timeoutsconnection 2source IP = the proxy'scan be reused by many clientsTwo 4-tuples (chapter 31), two sets of TCP state (chapter 16), two sets of idle timeouts (chapter 21).

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.

Office: the clients' sideFront desk PCStaff laptopForwardproxygoogle.comother sitesShopper 1Shopper 2Kadé: the servers' sideReverseproxykade-api-1kade-api-2

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 loggingOffices and schools block categories of sites and keep a record of who went where
Egress controlServers 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.
CachingOne download of a big update, shared by many machines (CDNs and HTTP caching are a separate topic for later)
PrivacySites 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:

Office PCOffice proxy :3128docs.google.comCONNECT docs.google.com:443the proxy checks its rules: is this site allowed?TCP handshakeHTTP/1.1 200 Connection establishedTLS ClientHello (SNI docs.google.com), relayed untouchedTLS handshake, then encrypted HTTP: the proxy only copies bytes

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:

#JobWhat it means for kade-apiChapter
1TLS terminationCertificates and handshakes live in one place; Node speaks plain HTTP25
2RoutingBy host or path: /api/* to kade-api, everything else to the frontend, so no CORS is needed28
3Load balancingSpread requests over several backends and skip broken onessection 4
4Buffering slow clientsA 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 up19
5Protocol translationHTTP/3 or HTTP/2 outside, HTTP/1.1 inside24
6ProtectionRate limits, a WAF (Cloud Armor on GCP), absorbing SYN floods16
7Compression, static files, cachinggzip/brotli responses; serve images without touching Nodelater topic
8Hiding the backendsThe VMs need no public IP at all10

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 proxyReverse proxy
1Sits withthe clientsthe servers
2Who configures itthe client (settings, env vars)nobody on the client: DNS simply points to it
3Hidesthe clientsthe servers
4HTTPSusually a blind CONNECT tunnelusually terminates TLS and reads everything
5Examplesoffice web filter, Squid, SSH -Dnginx, 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:

api.kade.lk → 34.120.88.10Shoppersbrowser · mobile appGoogle front endExternal Application LB34.120.88.10 · anycastTLS ends here (managed cert)Cloud Armor · URL mapadds X-Forwarded-Forkeeps a pool of connectionsto the backends:443kade-vpc · asia-southeast1instance group in sn-appkade-api-110.10.1.10:8080kade-api-210.10.1.11:8080Health checks35.191.0.0/16130.211.0.0/22kade-db10.10.2.5:5432Cloud NAT→ PayGate (outgoing)Before: api.kade.lk → 34.87.120.15, one VM.Now: no VM has a public IP at all.

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 load balancer: reads addresses and ports only
IP · 203.0.113.45 → 34.120.88.10TCP · :40001 → :443TLS-encrypted bytes: unreadable, just passed along
Layer 7 load balancer: ends TLS and reads the whole request
IPTCPTLS endsGET /orders/1042 · Host · cookies · headers
#Layer 4Layer 7
1Decides usingIP addresses and portsanything in the HTTP request: path, host, headers, cookies
2Balanceswhole connectionsindividual requests
3Protocolsanything on TCP/UDP: databases, MQTT, games, DNSHTTP(S), HTTP/2, HTTP/3, gRPC, WebSockets
4TLSpassed through (the backend holds the certificate), or simple terminationterminated; the LB holds the certificate
5Can dovery fast, very cheap per packetpath routing, redirects, header changes, retries, WAF, cookies for stickiness
6Client IP at the backendkept (passthrough), or via PROXY protocolvia X-Forwarded-For (section 9)
One trap with layer 4: HTTP/2 and gRPC put many requests on one long connection (chapter 24). A layer 4 balancer sends that whole connection to one backend, so one busy client can load one VM while the others sit idle. A layer 7 balancer spreads the individual requests.
#GCP load balancerLayerProxy?Typical use
1External Application LB7yesPublic websites and APIs: Kadé's choice
2Internal Application LB7yesHTTP between internal services
3External proxy Network LB4yes (TCP proxy)Non-HTTP TCP services from many regions
4Passthrough Network LB (external / internal)4no: packets pass through with the client's IPUDP, games, anything that must see the real client IP or do its own TLS

Choosing a backend

Round robin1, 2, 3, 1, 2, 3 … Simple and fair when requests are similar. GCP's default.
WeightedA bigger VM gets a bigger share; also used to send 5% to a new version (a "canary")
Least connections / least requestsPick the backend with the fewest requests in progress. Better when some requests are slow (reports, exports).
HashHash 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:

Algorithm
Next request from
time: 0 s
kade-api-110.10.1.10:8080healthy

in progress 0 · served 0

kade-api-210.10.1.11:8080healthy

in progress 0 · served 0

kade-api-310.10.1.12:8080healthy

in progress 0 · served 0

  1. 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 checksIt 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
Detection takes time: with the defaults, a crashed VM can still receive requests for up to about 10-15 seconds. Those requests fail, which is why clients should retry safe (idempotent) requests (chapter 24).

What should /healthz check? Two different questions are easy to mix up:

#QuestionShould includeCareful 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 overloadedShared 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).

#HowWorks byProblem
1CookieThe LB sets a cookie naming the backend (GCP's generated cookie is called GCLB)Needs cookies; only for HTTP (layer 7)
2Client IPA hash of the source IPEveryone behind one carrier NAT or office lands on the same VM; a phone moving from WiFi to 4G changes IP and "loses" its backend
3HeaderA hash of a header, e.g. a user IDThe client must send it
All stickiness has the same weaknesses: load gets uneven, and when the chosen VM dies or is redeployed, whatever it held in memory is lost anyway.

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 IPAll shoppers look like one IP: one busy user gets everyone blocked, or the limit never triggers
Logs and fraud checksEvery order was "placed from Google". The same problem NAT caused in chapter 10.
HTTPS detectionThe 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 URLsLinks in emails and redirects use the internal host and port

Proxies fix this by adding request headers that describe the original connection:

#HeaderKadé exampleMeaning
1X-Forwarded-For203.0.113.45, 34.120.88.10The client's IP. Each proxy appends the address it received the connection from, so the list grows left to right.
2X-Forwarded-ProtohttpsThe scheme the client used on the first connection
3X-Forwarded-Hostapi.kade.lkThe original Host, when a proxy changes it
4Forwardedfor=203.0.113.45;proto=httpsThe official standard version of all three; less widely used
5Via1.1 googleWhich proxies the request passed through
GCP's load balancer appends two entries: the client's IP and then the load balancer's own IP. Layer 4 proxies cannot add HTTP headers, so they use the PROXY protocol instead: one extra line at the start of the connection carrying the client's address.

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:

Path
Express trust proxy
HopX-Forwarded-For after this hopNote
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 balancer203.0.113.45, 34.120.88.10saw the connection come from 203.0.113.45; appends it, then its own IP
Node receives203.0.113.45, 34.120.88.10socket 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:

#HopRequest timeout (how long to wait for an answer)Idle timeout (how long an unused connection is kept)
1Kadé app / browserwhatever the code sets (fetch has none by default)browser's own
2GCP load balancerbackend service timeout: 30 s by default. Also the maximum life of a WebSocket (chapter 26).~10 minutes to clients and to backends (chapter 21)
3NoderequestTimeout 300 s, headersTimeout 60 skeepAliveTimeout: 5 s by default; must be longer than the LB's (set ~620 s)
4PostgreSQLstatement_timeout: none by defaultpool idle timeout (chapter 21)
Rule 1 · request timeoutsInner 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 timeoutsInner 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:

20 s
30 s
300 s →
none →
0 s30 s60 s90 s120 s
LayerTimeoutThis request
Kadé app gives up20 sgives up first
GCP load balancer (backend service timeout)30 swould give up
Node requestTimeout300 swaits
PostgreSQL statement_timeoutnonewaits

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:

#StatusWhat the LB is sayingExample GCP log detailUsual causes at KadéFix
1502 Bad Gateway"I reached a backend, but got a broken reply or none"backend_connection_closed_before_data_sent_to_clientNode's keep-alive shorter than the LB's (the race); Node crashed mid-requestkeepAliveTimeout ~620 s; check for crashes
2502"I could not connect to the backend"failed_to_connect_to_backendNode not listening on 8080, or listening on 127.0.0.1 only (chapter 31); firewallBind 0.0.0.0:8080; allow the LB ranges
3502 / 503"There is no healthy backend to pick"failed_to_pick_backendHealth checks failing on every VM: often the firewall blocks 35.191.0.0/16, or /healthz depends on the databaseCheck get-health; fix the firewall or the health endpoint
4504 Gateway Timeout (or 502)"The backend took too long"backend_timeoutA slow endpoint over 30 s, e.g. a big exportSpeed it up, make it a background job, or raise that route's timeout
5503 from your appYour code says "not now"response_sent_by_backendDraining, overloaded, or a deliberate maintenance responseExpected during deploys
The exact status for a timeout differs between GCP load balancer types; the log's 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:

#OptionShopper → LBLB → kade-apiTrade-off
1Terminate at the LBHTTPSHTTP inside the VPCSimplest; 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.
2Terminate and re-encryptHTTPSHTTPS (backend has its own certificate)Encrypted on every hop, for strict rules like card data; more certificates to manage
3PassthroughOne 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
4Mutual TLS at the LBHTTPS + a client certificateHTTP, plus headers saying who the client wasFor machine clients such as partners (chapter 25)

Common mistakes

#SymptomCauseFix
1All backends unhealthy right after setupFirewall does not allow 35.191.0.0/16 and 130.211.0.0/22Add an ingress rule for those ranges to port 8080
2A few random 502s per dayKeep-alive race (chapter 21)Node keepAliveTimeout longer than the LB's idle timeout
3Every request logged from 35.191.x.x; rate limiter blocks everyonetrust proxy not setSet it to the exact number of proxies
4"Too many redirects" after adding the LBApp thinks requests are httptrust proxy, so req.secure reads X-Forwarded-Proto; or let the LB do the http → https redirect
5WebSockets drop every 30 secondsGCP's backend service timeout caps WebSocket lifeRaise it for the WebSocket backend; reconnect with backoff anyway (chapter 26)
6Exports fail with 504, but the file still gets generatedRequest longer than the LB timeout; work continuesBackground job + "we'll email you the file"
7One VM hot, the other idleClient-IP stickiness behind carrier NAT, or HTTP/2 through a layer 4 LBCookie affinity or none; layer 7 balancing
8Errors on every deployVMs stopped without drainingFail readiness first, wait, then close (section 7)

Summary

#IdeaIn one lineNew terms
1ProxyTwo separate connections with a program copying between themproxy
2Forward proxyActs for clients: filtering, egress control; HTTPS via CONNECT tunnelsforward proxy, CONNECT, TLS inspection, PAC
3Reverse proxyActs for servers: TLS, routing, buffering, protection, one front doorreverse proxy
4Load balancerReverse proxy spreading traffic over backends; Kadé now uses 34.120.88.10backend, instance group
5L4 vs L7Ports and IPs vs full HTTP; connections vs requestspassthrough
6AlgorithmsRound robin, weighted, least requests, hashingcanary, consistent hashing
7HealthProbes and outlier detection; readiness vs liveness; draining on deployhealth check, draining
8StickinessCookie, IP or header affinity; prefer stateless backendssession affinity
9X-Forwarded-*Real client IP and scheme; trust only your own proxies' entriesX-Forwarded-For/Proto, PROXY protocol
10TimeoutsRequest timeouts shrink inward; idle timeouts grow inward; work continues after a timeoutbackend service timeout
11-125xx and TLS502 broken reply, 503 nothing available, 504 too slow; choose where TLS endsstatusDetails

Try it yourself

Headers added by a Google front end

curl -sI https://www.google.com | grep -i -E 'via|alt-svc|server'

How a proxy appends to X-Forwarded-For

curl -s -H 'X-Forwarded-For: 1.2.3.4' https://httpbin.org/headers

A CONNECT tunnel

curl -v -x http://PROXY:3128 https://example.com

Proxy settings your tools will use

env | grep -i proxy

What the LB thinks of each VM

gcloud compute backend-services get-health kade-api-backend --global

Recent 5xx and why

gcloud logging read 'resource.type="http_load_balancer" AND httpRequest.status>=500' --limit 10 --format='value(httpRequest.status,jsonPayload.statusDetails)'

Node's default timeouts

node -e "const s=require('http').createServer();console.log(s.keepAliveTimeout,s.headersTimeout,s.requestTimeout)"

Spotted a mistake, or something unclear? Suggest an edit on GitHub