Chapters

Load balancing 2: inside the HTTPS load balancer

Chapter 11 chose the global external Application Load Balancer for Kadé. It is not one object but a chain of five, and each link holds different settings. This chapter goes through the chain, then the settings that cause most real incidents: health checks, client IPs, certificates and Cloud Armor.

The front door · chapter 15 of 26 · 11 min read

A proxy load balancer is a chain, and each link does one job. Click a link to see what it holds, Kadé's value, and the question to ask it when something breaks. Knowing which link to look at is half of any load balancer problem.

requesthttps://…LINK 1Forwarding rulekade-https-rule34.120.88.10:443LINK 2Target proxykade-https-proxyTLS ends hereLINK 3URL mapkade-url-maphost + pathLINK 4Backend servicekade-api-backendArmor · CDN · logsLINK 5Backendkade-api-neg→ Cloud Run

1 · Forwarding rule · kade-https-rule

Holds
The IP address and port: the entry point. Also the scheme (EXTERNAL_MANAGED) and network tier.
Kadé's value
34.120.88.10:443 (kade-lb-ip, global, Premium)

Ask it when something breaks: "What IP is this on? Is it reserved, or ephemeral?"

Show as config
gcloud compute forwarding-rules describe kade-https-rule --global

The target proxy: where the connection ends

The forwarding rule is only an address, 34.120.88.10:443. It decides where a connection arrives, but something has to answer it, and the target proxy says how. It is not a machine you run, size or patch. It is a set of instructions that Google's front ends follow, at every edge location where a shopper can arrive (chapter 1.1). For a regional load balancer, the Envoy proxies in your proxy-only subnet follow them instead (chapter 2 section 06).

The instructions come down to three steps. Answer the TCP handshake. Prove to the browser that this really is kade.lk by showing its certificate, then agree on encryption. Decrypt, and read the HTTP request. Only after the third step is there a host and a path for the URL map to read.

Shopper203.0.113.99connection 1encryptedGoogle Front End, near the shopperkade-https-proxytarget HTTPS proxy1Ends TCPanswers the handshake2Ends TLSshows kade.lk's certificate,checks the TLS version3Reads HTTPHost: www.kade.lkGET /api/cartURL map/api/*backend servicekade-api-backendkade-apiCloud Runconnection 2a new one, openedby the front end
  • Google's front end, which runs the load balancer
  • Kadé's service
  • The settings Kadé writes: target proxy, URL map, backend service

Two connections, not one. The shopper's connection ends at the target proxy. The backend only ever sees connection 2, which the front end opens once the URL map and backend service have chosen where the request goes (chapter 11 section 05).

Wide by design - scroll it sideways.

Because the connection ends here, everything about the shopper's side of it is set here:

#Setting on the target HTTPS proxyWhat it decidesKadé's value
1Certificates, or a certificate mapWhich certificate it shows. The browser names the site it wants at the start of TLS (SNI), and the proxy picks the certificate for that namekade-cert-map
2SSL policyWhich TLS versions and ciphers it acceptskade-tls
3Server TLS policyWhether the client must show a certificate too (mTLS)Not used
4URL mapWho gets the decrypted requestkade-url-map
Section 07 covers the certificate choices and these policies in detail.

A load balancer has a target proxy exactly when it is a proxy. The kind of proxy decides how much it can read:

Application Load Balancer · reads HTTPforwarding ruleIP and porttarget HTTPS proxyor target HTTP proxyURL maphost + pathbackend servicewhere to send itbackendssee the proxyProxy Network Load Balancer · ends TCP, or TLS tooforwarding ruleIP and porttarget TCP proxyor target SSL proxyno URL mapbackend servicewhere to send itbackendssee the proxyPassthrough Network Load Balancer · ends nothingforwarding ruleIP and portno target proxy: packets pass through unreadbackend serviceregionalbackendssee the client
  • The target proxy: only proxy load balancers have one

The same chain, three ways. Take away the URL map and the load balancer can no longer route by path. Take away the target proxy too and nothing ends the connection: the backends see the client's own address.

Wide by design - scroll it sideways.

  • Target HTTPS proxy: ends TCP and TLS, reads HTTP. Kadé's kade-https-proxy.
  • Target HTTP proxy: ends TCP and reads HTTP, with no TLS. Kadé's kade-http-proxy exists only to answer port 80 with a redirect to HTTPS.
  • Target TCP proxy and target SSL proxy: the proxy Network Load Balancer. The SSL one ends TLS too, but neither reads HTTP, so they point straight at one backend service, with no URL map.
  • No target proxy: a passthrough Network Load Balancer. Its forwarding rule points straight at a backend service.

The URL map: where each request goes

The URL map can only route by host and path because the target proxy has already ended the connection and decrypted it. It works in two steps: a host rule picks a path matcher by hostname, then the path matcher picks a backend by the longest matching path. Anything that matches nothing goes to the default backend.

kade-static: backend bucket → Cloud Storage kade-static-assets (Cloud CDN, edge policy kade-static-edge)

  1. Host rule: "www.kade.lk" → path matcher "web".
  2. Path matcher "web": "/images/rice.jpg" matches "/images/*" (the longest matching path).

kade-url-map: host rule api.kade.lk → matcher "api" (everything → kade-api-backend); host rule www.kade.lk, kade.lk → matcher "web" (/api/* → kade-api-backend, /media/* → kade-media-backend, /images/* and /assets/* → kade-static, default kade-static); URL map default kade-static.

Backend types

A backend service points at one or more backends, the things that actually answer requests. What matters first is where the backend runs:

backend servicekade-api-backendIn your VPCManaged group (MIG)VMs from a templateUnmanaged groupa fixed list of VMsZonal NEGIP:port endpointsRun by Google, or published by someone elseServerless NEGCloud Run: kade-api-negPrivate Service Connect NEGa published serviceOutside Google CloudInternet NEGan IP or name anywhereHybrid NEGover VPN or Interconnectbackend bucketkade-staticCloud Storage bucketkade-static-assets · static files, no VMs
  • Run by Google
  • Your VPC
  • A load balancer setting Kadé writes

An instance group is a set of VMs. A network endpoint group (NEG) is a list of endpoints that need not be VMs: a Cloud Run service, an IP and port, or an address outside Google Cloud. A backend bucket takes the place of a backend service when the answer is a file in Cloud Storage.

Wide by design - scroll it sideways.

#BackendUse it for
1Managed instance groupVMs that scale and heal by themselves. The normal choice for VMs
2Unmanaged instance groupParticular existing VMs, as Kadé had with kade-api-1 and kade-api-2
3Serverless NEGCloud Run behind a load balancer. Kadé's kade-api-neg
4Zonal NEGContainers, where each pod is its own endpoint
5Internet NEGAn origin in another cloud, with Cloud CDN and Cloud Armor in front
6Hybrid NEGServers on-premises, reached privately (chapter 15)
7Private Service Connect NEGA published service (chapter 9)
Chapter 12.2 covers managed instance groups in depth: templates, autohealing, autoscaling and rolling updates.

Kadé's backend bucket kade-static serves www.kade.lk and /images/.

Health checks

For VM and zonal NEG backends, the load balancer probes each one and only sends traffic to those it marks healthy. Simple idea, three details that cause real incidents. Kadé's twenty-minute outage was the first one.

What if
1 · PROBE PATH: Google's health checkers → each VM, through the firewallHealth checkers35.191.0.0/16130.211.0.0/22GET /healthz :8080firewall (ingress)kade-lb-to-api: tcp:8080 from Google rangeskade-api-1app: running ✓health check✓ HEALTHYkade-api-2app: running ✓health check✓ HEALTHY2 · SHOPPER PATH: the load balancer only uses backends marked healthyShoppershttps://api.kade.lkload balancer2 healthy backendsserved by kade-api-1 and -2traffic shared across both

Health check probes come from Google's ranges 35.191.0.0/16 and 130.211.0.0/22, not from the load balancer IP. A dedicated rule lets them reach port 8080, both VMs answer, and both are marked healthy.

Show as config
Health check kade-hc: HTTP, port 8080, path /healthz
Firewall kade-lb-to-api: allow tcp:8080 from 35.191.0.0/16, 130.211.0.0/22 → sa-kade-api
#Load balancerProbe source ranges your firewall must allow
1Application and proxy Network load balancers, internal passthrough NLB35.191.0.0/16, 130.211.0.0/22
2External passthrough Network LB35.191.0.0/16, 209.85.152.0/22, 209.85.204.0/22
Give the probes a dedicated rule (Kadé's was kade-lb-to-api, chapter 5.1). Then deleting a broad catch-all rule never breaks the health path by accident.

Balancing across healthy backends

#Setting (on the backend service)What it controlsValues
1Balancing modeWhen a backend counts as "full". At the target, traffic spills to other backends or a MIG scales outUTILIZATION (CPU), RATE (requests per second), CONNECTION
2Session affinityKeeps one client on the same backendNONE, CLIENT_IP, GENERATED_COOKIE, HTTP_COOKIE, HEADER_FIELD
3Connection drainingHow long a backend being removed may finish the requests it already hasSeconds
4TimeoutHow long to wait for a backend's response30 s by default; not used for serverless NEGs

Balancing mode is the one that decides where traffic goes. Each group has a target, and a group at its target counts as full:

load balancermode: RATEdashed: only what isover the targetnearest grouptarget: 80 req/s per VMat the target: counts as fullfilled to the targetnext grouptakes the overflowa MIG can add VMs insteadroom left
  • Run by Google
  • Your VPC
  • Allowed traffic and replies

Wide by design - scroll it sideways.

Session affinity is needed only when a backend keeps a shopper's state in its own memory:

No affinityShopperVM 1cart in memoryVM 2no cart: looks emptyWith affinityShopperVM 1every requestVM 2other shoppers
  • Your VPC
  • Allowed traffic and replies

Affinity fights even balancing, and it breaks when that VM goes away. The cleaner design is backends that keep nothing, with the cart in Redis or the database.

Wide by design - scroll it sideways.

Timeout: too short cuts off slow but valid responses, such as a large report. Too long lets a stuck backend hold connections. Set it just above your slowest legitimate request.

A deploy without downtime is mostly these settings and the health check working together. The chart follows a rolling update of a two-VM group, as Kadé did before chapter 10:

What if
old VM removed from rotationold VMversion 1servingdraining: finishes in-flight requestsnew VMversion 2bootingcheck failingservingshoppersstops0 s30 s60 s90 s120 s150 s

Zero failed requests during the deploy

The new VM gets traffic only after its HTTP health check passes. The old VM stops getting new requests, then has 60 s of connection draining to finish the ones it has, and only then shuts down. No request fails.

Show as config
Backend service: connectionDraining.drainingTimeoutSec: 60
Health check: HTTP /healthz (returns 200 only when the app is fully ready)
MIG update: maxSurge 1, maxUnavailable 0

The real client IP

Builds on33. X-Forwarded-For

Behind a proxy, the backend's network connection comes from Google's front end, not the shopper (chapter 11 section 05). The shopper's address travels in a header instead. Getting this wrong was the second problem at the top of this chapter, and it also has a security side:

What if
Shopper203.0.113.99Google Front End34.120.88.10kade-apiCloud Run

X-Forwarded-For as kade-api receives it

  1. 203.0.113.99added by Google: the client it saw
  2. 34.120.88.10added by Google: the LB itself

Which entry to trust

The second entry from the end is the client Google saw: 203.0.113.99.

Client sent X-Forwarded-For: (none)

Google's front end appends two addresses to X-Forwarded-For: the client it saw, then the load balancer's own IP. The client's address is therefore the second from the end. Log the raw header once in your own setup to confirm the count before relying on it.

Show as config
GCP adds:  X-Forwarded-For: <whatever the client sent>, <client IP>, <load balancer IP>
Shopper:   X-Forwarded-For: 203.0.113.99, 34.120.88.10
Spoofed:   X-Forwarded-For: 1.2.3.4, 203.0.113.99, 34.120.88.10
#Header the load balancer addsContains
1X-Forwarded-ForWhatever the client sent, then client IP, load balancer IP appended
2X-Forwarded-Protohttps or http: how the client connected
3Via1.1 google
4Custom request headers you defineValues like {client_region}, {client_city} or {tls_version}, filled in per request

TLS and certificates

Builds on25. TLS and HTTPS

TLS ends at the target proxy, which is where certificates are attached (section 01). Before Google issues a certificate, it checks that you own the domain. There are two ways, and the difference decides what works behind Cloudflare:

Load balancer authorizationGoogle checksconnects to kade.lkfollows the A recordA record → load balancer34.120.88.10 · certificate issuedA record → Cloudflare (chapter 13)check fails · no certificateDNS authorizationGoogle checkslooks up one record_acme-challenge.kade.lkCNAME record, added onceissued · wherever kade.lk points
  • Google, issuing the certificate
  • Certificate issued

Wide by design - scroll it sideways.

The full choice, including bringing your own certificate:

#Google-managed, load balancer authorizationGoogle-managed, DNS authorizationSelf-managed
1Who issuesGoogleGoogleYou, from any certificate authority
2How Google checks you own the domainThe domain's A record must already point at the load balancer IPA CNAME record you add once in DNSNot its job
3RenewalAutomaticAutomaticYours to remember
4Wildcards (*.kade.lk)NoYesYes
5Works behind Cloudflare's proxyOften fails: the domain points at Cloudflare, not the load balancerYesYes
6Set up withA Compute Engine SSL certificate resourceCertificate ManagerEither
The self-managed failure is predictable: a certificate uploaded by hand expires a year later, and the site starts showing certificate errors. Google-managed certificates exist to remove that failure.

One load balancer address can serve many hostnames, each with its own certificate. The browser names the site it wants at the start of TLS (this is called SNI), and the certificate map picks:

BrowserTLS hello: api.kade.lkkade-cert-mapkade.lk*.kade.lk · matchescertificate shownthe one for *.kade.lk
  • What the browser gets
  • A load balancer setting Kadé writes

Wide by design - scroll it sideways.

#Other TLS objectWhat it doesKadé's value
1SSL policyWhich TLS versions and ciphers the load balancer accepts. Profiles: COMPATIBLE (the permissive default), MODERN, RESTRICTED, CUSTOM, plus a minimum TLS versionkade-tls: MODERN, minimum TLS 1.2
2Certificate mapLets one load balancer serve many certificates, picking one per hostnamekade-cert-map with kade.lk, *.kade.lk
3mTLSThe client also shows a certificate, and the load balancer checks it. Only clients with a valid certificate can connect at allNot used; a fit for a partner API

Cloud Armor: the WAF

Cloud Armor is attached to a backend service (link 4 of the chain). It looks at each request at Google's front end, before it reaches your backends, and allows, denies, or rate-limits it. Unlike the VPC firewall, it sees the real client IP and the request itself (chapter 5.2).

What matters at this point is where it attaches and how it can be bypassed:

What if
internetrequestskade-lb (shop)forwarding rule → proxy→ URL mapkade-api-backendCloud Armor: kade-edge-policyinspectedbackendsinternetrequestsadmin-lb (internal tools)forwarding rule → proxy→ URL mapadmin-backendCloud Armor: nonenot inspectedbackends

One load balancer has a WAF, the other has none

Cloud Armor attaches to a backend service, not to the whole load balancer. Here one load balancer's backend service has a policy and the other's does not, so the second front door has no WAF at all, even for traffic that does go through a load balancer. This is how real projects end up with uneven coverage. Check with command 4.

Show as config
kade-api-backend    securityPolicy: kade-edge-policy
admin-backend       securityPolicy: (none)
How rules are written, the ready-made WAF rules, rate limits and a safe rollout are all in chapter 12.3.

Cloud CDN

Cloud CDN caches responses at Google's edge locations, so repeated requests are answered near the user without reaching the backend. It is turned on per backend service or backend bucket, the same place Cloud Armor attaches. Kadé turns it on for kade-static, with the cache mode CACHE_ALL_STATIC: static files such as product images are cached, and nothing from the API is.

What gets cached and for how long, the cache key, replacing a cached file and reading hits in the logs are all in chapter 12.4. Chapter 13 adds Cloudflare's cache in front.

Logs: who answered?

Request logging is turned on per backend service, with a sample rate. Each log line has a statusDetails field that says who produced the response, which settles most "is it the load balancer or the app?" arguments:

ShopperCloud CDNresponse_from_cacheanswered from the cacheCloud Armordenied_by_security_policya rule refused itpick a backendfailed_to_pick_backendnone is healthybackendresponse_sent_by_backendthe app answeredbackend_timeoutno answer in timebelow each stage:the statusDetails it writes when it answers
  • Run by Google
  • Your backend
  • Allowed traffic and replies
  • Cloud Armor

A 500 with response_sent_by_backend is an app bug. failed_to_pick_backend sends you to the health checks (section 04). denied_by_security_policy comes with enforcedSecurityPolicy, which names the rule (chapter 12.3).

Wide by design - scroll it sideways.

Back to Kadé

Commands in this chapter

Commands 1 to 7 are read-only. Commands 8 to 10 change the project.

Follow the chain from the IP

  • What it shows: The forwarding rule's target proxy, then that proxy's URL map and certificate setup.
  • What to look for: Which proxy each forwarding rule uses, and whether the HTTPS proxy has a certificate map and an SSL policy.
gcloud compute forwarding-rules describe kade-https-rule --global --format="value(target)"gcloud compute target-https-proxies describe kade-https-proxy \  --format="yaml(urlMap,certificateMap,sslCertificates,sslPolicy)"

See how the URL map routes

  • What it shows: Host rules, path matchers and the default service.
  • What to look for: Every hostname you serve has a host rule, and the default service is what you expect for unknown hosts.
gcloud compute url-maps describe kade-url-map --format="yaml(defaultService,hostRules,pathMatchers)"

Check a backend service's protection and settings

  • What it shows: Cloud Armor policy, CDN, logging, timeout, affinity and backends.
  • What to look for: An empty securityPolicy means no WAF on this backend service.
gcloud compute backend-services describe kade-api-backend --global \  --format="yaml(securityPolicy,enableCDN,logConfig,timeoutSec,sessionAffinity,backends)"

Find backend services with no Cloud Armor policy

  • What it shows: Every backend service and its security policy, in one table.
  • What to look for: A blank policy on anything public-facing. This is the "WAF on some load balancers but not others" check.
gcloud compute backend-services list \  --format="table(name,loadBalancingScheme,securityPolicy.basename())"

See backend health (VM or zonal NEG backends)

  • What it shows: Each backend instance and whether the health check passes.
  • What to look for: UNHEALTHY while the app works means the probe path: firewall rule, port, or health check path.
gcloud compute backend-services get-health kade-api-backend --global

Check certificate status

  • What it shows: Each Certificate Manager certificate, its domains and its state.
  • What to look for: ACTIVE. PROVISIONING for a long time usually means the DNS authorization record is missing.
gcloud certificate-manager certificates list \  --format="table(name,sanDnsnames.list(),managed.state,expireTime)"

Read load balancer logs for errors

  • What it shows: Recent requests with status 5xx, and who produced each response.
  • What to look for: The statusDetails value (section 10).
gcloud logging read \  'resource.type="http_load_balancer" AND httpRequest.status>=500' \  --freshness=1h --limit=20 \  --format="table(timestamp,httpRequest.status,jsonPayload.statusDetails,httpRequest.requestUrl)"

Attach a Cloud Armor policy to a backend service (changes the project)

  • What it shows: Puts kade-edge-policy in front of kade-api-backend.
  • What to look for: The policy name in command 4. Repeat for every public backend service.
gcloud compute backend-services update kade-api-backend --global \  --security-policy=kade-edge-policy

Add a WAF rule in preview mode first (changes the project)

  • What it shows: A SQL injection rule that only logs what it would block.
  • What to look for: Matches in the logs with previewSecurityPolicy. When there are no false positives, update the rule with --no-preview.
gcloud compute security-policies rules create 1000 --security-policy=kade-edge-policy \  --expression="evaluatePreconfiguredWaf('sqli-v33-stable')" --action=deny-403 --preview

Require modern TLS (changes the project)

  • What it shows: Creates the SSL policy and attaches it to the HTTPS proxy.
  • What to look for: sslPolicy set in command 1. Very old clients that only speak TLS 1.0 can no longer connect.
gcloud compute ssl-policies create kade-tls --profile=MODERN --min-tls-version=1.2gcloud compute target-https-proxies update kade-https-proxy --ssl-policy=kade-tls

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

See it broken

Harbour is a platform built wrong on purpose. These defects are this chapter's ideas, left undone: what each one breaks, how you would find it, and the change that closes it.

  1. D13
    TCP health check on a web backend

    mediumcloses in phase 5, Egress and load balancer

    Goes with Health checks

  2. D14
    No Cloud Armor on the legacy backend service

    highcloses in phase 5, Egress and load balancer

    Goes with Cloud Armor: the WAF

  3. D15
    No SSL policy on the HTTPS proxy

    mediumcloses in phase 5, Egress and load balancer

    Goes with TLS and certificates