CloudBrum
CloudBrum · Cloud decision-support platform
Google Cloud Networking

Cloud Load BalancingLast reviewedReading time~12 minLevelBeginner to advanced

Google Cloud · Networking · Application and Network load balancers, global and regional

Cloud Load Balancing is Google’s family of managed load balancers, and its defining trait is that most of it is not a machine at all. A global external Application Load Balancer gives a service one anycast IP address that works from anywhere, terminates TLS at Google’s edge, routes by URL and sends each request to the closest healthy backend, with nothing to size, warm up or patch. The price of that flexibility is choice: there are about a dozen variants, and picking the right one, with the right network tier, is most of the design work.

On this page (17 sections)

    Mind map: Cloud Load Balancing at a glance

    Cloud Load Balancing mind map Cloud Load Balancing at a glance: Types: Application (layer 7), Proxy Network (layer 4), Passthrough Network; Scope and tier: Global, one anycast IP, Regional, Premium and Standard tier; Front end: Forwarding rule, Target proxy, Certificates and SSL policy; Routing: URL map, Host and path rules, Traffic splitting; Backends: Instance groups, NEGs, serverless NEGs, Backend buckets; Health: Health checks, Outlier detection, Failover; Protection: Cloud Armor, Cloud CDN, Identity-Aware Proxy; Pricing: Forwarding rule hours, Data processed, Egress, Cloud Armor. Cloud Load Balancing at a glance Load balancing on Google Cloud: the main building blocks and decisions CloudBrum Cloud decision-support platform CloudBrum Application (layer 7) Proxy Network (layer 4) Passthrough Network Types Global, one anycast IP Regional Premium and Standard tier Scope and tier Forwarding rule Target proxy Certificates and SSL policy Front end URL map Host and path rules Traffic splitting Routing Instance groups NEGs, serverless NEGs Backend buckets Backends Health checks Outlier detection Failover Health Cloud Armor Cloud CDN Identity-Aware Proxy Protection Forwarding rule hours Data processed Egress, Cloud Armor Pricing Load Balancing17-point analysis CloudBrum· 17-point cloud service analysis cloudbrum.com
    CloudBrum Load Balancing at a glance · 17-point analysis Types Application (layer 7) Proxy Network (layer 4) Passthrough Network Scope and tier Global, one anycast IP Regional Premium and Standard tier Front end Forwarding rule Target proxy Certificates and SSL policy Routing URL map Host and path rules Traffic splitting Backends Instance groups NEGs, serverless NEGs Backend buckets Health Health checks Outlier detection Failover Protection Cloud Armor Cloud CDN Identity-Aware Proxy Pricing Forwarding rule hours Data processed Egress, Cloud Armor CloudBrum · cloudbrum.com

    Free to share. The downloaded image includes the CloudBrum link.

    Key features (summary)

    • One address for the worldA global external load balancer has a single anycast IP address. Visitors enter Google’s network at the nearest edge location, and traffic is carried to the closest backend that has capacity, in any region.
    • Application and Network familiesApplication Load Balancers work on HTTP and HTTPS. Proxy Network Load Balancers terminate TCP connections, with optional TLS. Passthrough Network Load Balancers forward packets untouched, so the backend sees the client’s address.
    • URL mapsA URL map matches host, path and header rules and then routes, redirects or rewrites. It can split traffic by weight between backends, which makes canary releases a configuration change, and it can mirror requests to a test backend.
    • Backends of many kindsManaged and unmanaged instance groups, network endpoint groups for VMs and containers, serverless NEGs for Cloud Run, Cloud Run functions and App Engine, internet NEGs for servers outside Google Cloud, and Cloud Storage buckets.
    • Health checks and failoverHealth checks over HTTP, HTTPS, gRPC or TCP take unhealthy backends out of rotation. Outlier detection ejects backends that return errors, and traffic overflows to other zones or regions when a backend is full.
    • Cloud Armor and TLSCloud Armor security policies add WAF rules, rate limits and geographic controls in front of the backends. Google-managed certificates and SSL policies handle TLS at the edge.
    • Nothing to size or warm upThere are no load balancer instances to choose or to pre-warm. Capacity is Google’s concern, so the limits that you plan around are your backends' capacity and your quotas.
    • Two network tiersPremium Tier carries traffic across Google’s own network from the nearest edge. Standard Tier hands it to the public internet earlier at a lower price, and is available for regional external load balancers only.

    Basic concepts

    Forwarding rule
    A rule that owns an IP address and port, and sends the traffic that arrives there to a target proxy or a backend service.
    Target proxy
    The component that terminates the connection for Application and proxy Network Load Balancers. It holds certificates and the URL map.
    URL map
    Routing rules for an Application Load Balancer: which host and path goes to which backend service or bucket, and what is redirected or rewritten.
    Backend service
    Describes a group of backends and how to use them: protocol, timeout, health check, balancing mode, session affinity, logging and Cloud Armor policy.
    Network endpoint group (NEG)
    A set of endpoints used as a backend: VM IP and ports, a serverless service, an internet host name or an on-premises address.
    Health check
    A probe that decides whether a backend can take traffic. Google’s probe addresses are 130.211.0.0/22 and 35.191.0.0/16, and firewalls must allow them.
    Balancing mode and capacity
    Utilization, rate or connections decide how much a backend should receive before the load balancer prefers another. A capacity scaler adjusts it.
    Session affinity
    Sends a client to the same backend, by client IP, cookie or header, when the application needs it.
    Network Service Tier
    Premium or Standard. It decides how far traffic travels inside Google’s network, and it changes egress price and which load balancers you can use.
    Proxy and passthrough
    A proxy load balancer ends the client connection and opens a new one to the backend. A passthrough load balancer forwards packets, so the original connection and client IP reach the backend.
    Serverless NEG
    A backend that points at a Cloud Run, Cloud Run functions or App Engine service, so that serverless apps can sit behind a load balancer with a custom domain, Cloud Armor and CDN.
    Proxy-only subnet
    A subnet that regional Envoy-based load balancers use for their proxies. It needs to exist in each region and network where you create one.
    Cloud Armor policy
    A set of rules, including WAF, rate limiting and IP allow and deny lists, attached to a backend service.

    How to create & configure it

    Put a Cloud Run service behind a global load balancer with gcloud

    1. Choose the load balancerFor web traffic from the internet use a global external Application Load Balancer. For TCP or UDP use a Network Load Balancer, proxy or passthrough. For traffic inside a network use an internal one.
    2. Create the backendHere a serverless NEG points at a Cloud Run service. For VMs you would use an instance group or a zonal NEG and add a health check.
    3. Create the backend service and turn on loggingUse the external managed scheme, enable request logging and keep full sampling at first, so you can see what happens to real traffic.
    4. Attach a Cloud Armor policyStart with a rate limit and managed rules, and tune them with the logs.
    5. Build the front endA global address, a URL map, a Google-managed certificate, an HTTPS proxy and a forwarding rule on port 443.
    6. Add the redirectA second forwarding rule on port 80 uses a URL map that only redirects to HTTPS.
    7. Point DNS and wait for the certificateCreate an A record to the address. The managed certificate becomes active after DNS resolves.
    8. Open the firewall for health checks (VM backends)Allow the health check ranges to reach the backend port, or every backend will look unhealthy.
    9. Watch the logs and metricsThe log field statusDetails explains every error response. Alert on 5xx rates, latency and backend health.

    Tip: for backends that keep connections open, make the web server’s keep-alive timeout longer than the load balancer’s (10 minutes for global external Application Load Balancers). If the server closes first, an idle connection can be reused just as it dies, and users see sporadic 502 errors. See the code references for the same setup as Terraform.

    Common issues after configuration

    SymptomLikely causeWhat to check / fix
    502 with failed_to_connect_to_backendThe load balancer couldn’t open a connection: the service isn’t listening, a firewall blocks Google’s ranges, or the backend is downAllow 130.211.0.0/22 and 35.191.0.0/16 (and the proxy-only subnet for regional load balancers) to the backend port, and check the service.
    Sporadic 502 with backend_connection_closed_before_data_sent_to_clientThe backend closed a keep-alive connection that the load balancer was about to reuseRaise the backend’s keep-alive timeout above the load balancer’s, which is 600 seconds for global external Application Load Balancers.
    504 with backend_timeoutThe backend didn’t answer within the backend service timeout (30 seconds by default)Raise the timeout for long requests such as uploads or WebSockets, and fix slow backends.
    503 with failed_to_pick_backendNo healthy backend is availableLook at backend health in the console or get-health, and fix the health check or the service.
    Every backend is unhealthy but the app worksThe health check path, port or protocol is wrong, or the firewall blocks the check rangesMatch the health check to what the app serves, and add the firewall rule for the check ranges.
    403 and denied_by_security_policyA Cloud Armor rule matched the requestLook at the matched rule in the log, run new rules in preview mode first, and adjust or exclude false positives.
    The managed certificate stays in PROVISIONINGDNS doesn’t point at the forwarding rule’s address yet, or another record or a CAA record interferesCreate the A record for the load balancer’s IP, remove conflicting records and wait.
    The application sees the load balancer’s addressA proxy load balancer opens its own connection to the backendRead the client address from X-Forwarded-For, or use a passthrough Network Load Balancer, which keeps the source address.
    HTTP requests aren’t redirected to HTTPSOnly an HTTPS forwarding rule exists, so port 80 has nothing listeningAdd a forwarding rule on port 80 with a URL map that redirects to HTTPS.
    Traffic is uneven between zones or regionsThe balancing mode and capacity send traffic by utilization, rate or connections, and session affinity pins clientsChoose the balancing mode that matches the workload, tune capacity scalers and limit affinity.
    The bill is higher than expectedForwarding rule hours add up, data processed and egress are billed per GiB, and Cloud Armor adds its own chargesMerge forwarding rules onto fewer IPs, put Cloud CDN in front of cacheable content, and compare Premium and Standard tier egress.

    Use cases: when and where to use it

    Good fit

    • Internet-facing web apps and APIs that need one global address and TLS at the edge
    • Cloud Run and Cloud Run functions apps that need a custom domain, Cloud Armor or a CDN
    • Multi-region services that should send each user to the nearest healthy region
    • TCP and UDP services that need very fast, proxy-free forwarding with the client IP preserved
    • Internal services that need layer 7 routing between microservices inside a network
    • Canary and blue/green releases using weighted backends in the URL map

    Consider something else

    • Caching static content at the edge → Cloud CDN on the same load balancer
    • Running the web app without managing a load balancer at all → Cloud Run with its own domain mapping
    • Pod-level routing inside Kubernetes → Google Kubernetes Engine Gateway and Ingress, which create these load balancers for you
    • DNS records and routing policies → Cloud DNS
    • Private connectivity to a service in another network → Private Service Connect
    • The same job on other clouds → compare Elastic Load Balancing and Azure Load Balancer

    Pros: why consider it?

    Why teams choose it

    • One global anycast address with no instances to size or pre-warm
    • Rich routing, redirects, rewrites and traffic splitting in the URL map
    • Serverless NEGs put Cloud Run and functions behind a custom domain, Cloud Armor and CDN
    • Cloud Armor, managed certificates and Cloud CDN plug in directly
    • Passthrough Network Load Balancers keep the client IP and add almost no latency
    • Detailed logs with a status detail that names the cause of an error

    Trade-offs to weigh

    • Many variants, with differences in scope, tier and features that take time to learn
    • Global external load balancers require the Premium Network Service Tier
    • Several pieces to wire up: forwarding rule, proxy, URL map, backend service and certificate
    • Forwarding rules and data processed are billed on top of egress
    • Health checks need firewall rules, and a missing one makes every backend look unhealthy
    • Regional Envoy-based load balancers need a proxy-only subnet in each region

    Common threats, vulnerabilities & risks

    RiskSeverityWhy it mattersMitigation
    No Cloud Armor policy on a public backendHighBots, floods and common attacks reach the application unfiltered.Attach a policy with rate limits and managed rules, and test new rules in preview mode.
    Backends reachable directlyHighInstances with external IPs or open firewall rules let attackers skip the load balancer.Remove public IPs, and allow only the load balancer and health check ranges to the backend.
    Serving content over plain HTTPHighTraffic on port 80 can be read or changed on the way.Redirect port 80 to HTTPS and set a modern SSL policy.
    Unhealthy backends hidden by weak health checksMediumA check that always passes sends users to broken servers, and one that is too strict removes everything.Check what matters in the service, and tune thresholds from the logs.
    Wrong Network Service TierMediumStandard Tier can add latency across regions, and Premium costs more for egress.Choose per workload, and compare latency and cost before committing.
    A single region behind a regional load balancerMediumA regional outage takes the application down.Use a global external load balancer with backends in two or more regions where the data layer allows it.
    Request logging switched offMediumWithout logs you can’t tell attacks, errors and slow backends apart.Enable logging with a sample rate that fits your volume, and send alerts from log-based metrics.
    Large changes made by handLow–MedA manual change to a URL map or backend can break routing for everyone.Keep load balancers in code, review changes and use traffic splitting to roll out.
    Orphaned forwarding rules and addressesLow–MedEach reserved address and rule bills hourly, even unused.Label with an owner and review monthly.

    Performance optimisation

    • Use a global external Application Load Balancer with backends in the regions where your users are, so each request travels to the nearest healthy one.
    • Keep the backend keep-alive timeout above 600 seconds for global external load balancers, to avoid reused-connection errors.
    • Choose the balancing mode that fits: rate for web requests, utilization for CPU-bound work, connections for long-lived flows.
    • Turn on Cloud CDN for cacheable content, so many requests never reach the backends.
    • Use HTTP/2 and HTTP/3 on the front end and let clients negotiate them.
    • Use outlier detection and health checks with sensible thresholds, so bad backends leave quickly and return only when healthy.
    • Set the backend service timeout to the longest request you expect, not an arbitrary high value.
    • Place backends and data close together, because a fast load balancer can’t hide a slow database.

    Reduce monthly cost

    FinOps is the habit of managing cloud spend together with engineering. These are the FinOps checks that matter most for Cloud Load Balancing.

    • Share one IP address and forwarding rule between several services with host and path rules, where the design allows.
    • Delete unused forwarding rules, addresses and backends, since each bills by the hour.
    • Put Cloud CDN in front of cacheable content, because cache hits don’t pass through the load balancer.
    • Compare Premium and Standard Network Service Tier for regional external load balancers.
    • Cut data processed with compression and caching, since it is billed per GiB.
    • Watch egress, which is billed separately from load balancing, and keep traffic in-region where you can.
    • Add Cloud Armor rate limits, which stop abusive traffic that would otherwise raise data charges.
    • Check whether Cloud Run’s own domain mapping or a simple regional load balancer is enough before building a global one.
    • Review the logging sample rate, since logs have their own cost at very high volume.
    • Label resources by team and set a budget alert on the project.

    Figures here come from Google's pricing page and published guides, read in October 2026. Sources show example rates and the real ones depend on region and type, so check the live page (see Pricing).

    Security optimisation

    • Attach Cloud Armor policies with rate limits, managed WAF rules and, where needed, geographic restrictions.
    • Use Google-managed certificates and a modern SSL policy with a minimum TLS version.
    • Redirect HTTP to HTTPS on a separate port-80 front end.
    • Allow only Google’s health check ranges and the load balancer’s addresses to reach backends, and keep backends off public IPs.
    • Use Identity-Aware Proxy for internal tools that need per-user access control.
    • Turn on request logging, and send logs to a restricted sink for audit.
    • Restrict who can change load balancers, URL maps and Cloud Armor policies with IAM, and alert on changes.
    • Use private connectivity (internal load balancers, Private Service Connect) for services that shouldn’t be public.
    • Keep secrets out of URL maps and headers, and use Secret Manager for credentials.
    • Review Security Command Center findings for the project, including open firewall rules.

    Governance & compliance

    Guardrails

    • A shared Terraform module that creates load balancers with Cloud Armor, logging, an HTTPS redirect, a modern SSL policy and labels
    • An organisation policy and IAM review that limits who can create external load balancers and public addresses
    • A naming standard for forwarding rules, URL maps and backend services, with the owner and the purpose of each recorded
    • A release practice that uses weighted backends in the URL map for canaries, with a documented rollback

    Continuous checks (Cloud Asset Inventory, Security Command Center and your own scripts)

    • A scheduled script that lists external backend services without Cloud Armor or logging, and HTTP proxies that don’t redirect (the C# tab does this)
    • Security Command Center and organisation policy findings for public addresses and open firewall rules
    • Alerts on 5xx rate, backend latency and unhealthy backend counts
    • An audit-log alert for changes to URL maps, backend services and security policies
    • A monthly report of forwarding rules and addresses with no traffic

    Cloud Audit Logs show who changed a load balancer or policy, Cloud Asset Inventory stores past configurations, Security Command Center reports posture, and Google’s compliance reports manager holds certifications. Google runs the load balancing infrastructure. Routing design, Cloud Armor rules, certificates, firewall rules for backends and what the logs keep are yours.

    Reduce carbon footprint

    • Delete idle forwarding rules, addresses and backends.
    • Use Cloud CDN and compression so fewer bytes cross the network.
    • Keep backends in a region close to users and data, and use autoscaling so capacity follows load.
    • Merge services behind shared load balancers where it is safe to do so.
    • If data rules and latency allow, place backends in a Google Cloud region that Google marks as low carbon.
    • Google’s Carbon Footprint report is per project and service group, so quote no Cloud Load Balancing-only figure.

    Pricing

    Purchase options

    Forwarding rules From $0.025 an hour

    About $0.025 per hour for each of the first five rules and $0.01 for each more. Each forwarding rule bills by the hour. Rates quoted on Google’s pricing page for external and internal rules differ by type and region.

    Data processed Per GiB processed

    For example $0.008 per GiB in one region. Billed for the traffic that passes through the load balancer in both directions, at rates that vary by region and load balancer type. Cache hits don’t pass through it.

    Network egress Per GiB, by tier and destination

    Data leaving Google Cloud is billed under network pricing, and the Premium and Standard Tiers have different egress rates.

    Related products Cloud Armor, Cloud CDN, certificates

    Cloud Armor policies and requests, Cloud CDN egress, fills and lookups and logging are billed on their own. Google-managed certificates are free.

    What you actually pay for

    • Forwarding rule hours, by type of rule
    • Data processed through the load balancer, per GiB
    • Network egress to the internet and between regions
    • Cloud Armor policies, rules and requests, and Cloud CDN charges
    • Reserved external IP addresses that aren’t in use

    Google lists forwarding rule and data processing rates on its pricing page, and rates differ by region and load balancer type. See the official Cloud Load Balancing pricing page and the Google Cloud Pricing Calculator.

    Important code references

    A Cloud Run service behind a global external Application Load Balancer: a serverless NEG, a backend service with logging, a Cloud Armor rate limit, a URL map, a Google-managed certificate, an HTTPS front end and an HTTP front end that redirects. The CLI tab builds it and reads the error logs; Terraform describes the same resources. The Python tab counts recent 5xx responses by the reason the load balancer logged, and the C# tab audits backend services for missing Cloud Armor and logging, and HTTP proxies that don’t redirect. Replace the project, region, service and domain with your own.

    # Placeholders: replace the project, the region, the Cloud Run service and the domain with your own.
    PROJECT=my-project-id
    REGION=asia-south1
    SERVICE=hello
    DOMAIN=app.example.com
    
    # 1. A serverless network endpoint group that points at an existing Cloud Run service. Cloud Run needs no health check:
    #    the load balancer treats the whole service as one backend and Cloud Run scales behind it.
    gcloud compute network-endpoint-groups create hello-neg --project $PROJECT --region $REGION \
      --network-endpoint-type serverless --cloud-run-service $SERVICE
    
    # 2. A backend service for the global external Application Load Balancer, with request logging at full sampling.
    gcloud compute backend-services create hello-backend --project $PROJECT --global --load-balancing-scheme EXTERNAL_MANAGED \
      --protocol HTTPS --enable-logging --logging-sample-rate 1.0
    gcloud compute backend-services add-backend hello-backend --project $PROJECT --global \
      --network-endpoint-group hello-neg --network-endpoint-group-region $REGION
    
    # 3. A Cloud Armor policy that slows any client sending more than 100 requests a minute. Attach it to the backend service.
    gcloud compute security-policies create edge-policy --project $PROJECT --description "Rate limit per client"
    gcloud compute security-policies rules create 1000 --project $PROJECT --security-policy edge-policy --expression "true" \
      --action throttle --rate-limit-threshold-count 100 --rate-limit-threshold-interval-sec 60 \
      --conform-action allow --exceed-action deny-429 --enforce-on-key ip
    gcloud compute backend-services update hello-backend --project $PROJECT --global --security-policy edge-policy
    
    # 4. The front end: a global address, a URL map, a Google-managed certificate, an HTTPS proxy and a forwarding rule.
    gcloud compute addresses create app-ip --project $PROJECT --global
    gcloud compute url-maps create app-map --project $PROJECT --default-service hello-backend
    gcloud compute ssl-certificates create app-cert --project $PROJECT --domains $DOMAIN --global
    gcloud compute target-https-proxies create app-proxy --project $PROJECT --url-map app-map --ssl-certificates app-cert
    gcloud compute forwarding-rules create app-https --project $PROJECT --global --address app-ip --target-https-proxy app-proxy \
      --ports 443 --load-balancing-scheme EXTERNAL_MANAGED
    
    # 5. A second front end on port 80 that only redirects to HTTPS, on the same address.
    cat > redirect.yaml <<YAML
    name: app-redirect
    defaultUrlRedirect:
      httpsRedirect: true
      redirectResponseCode: MOVED_PERMANENTLY_DEFAULT
    YAML
    gcloud compute url-maps import app-redirect --project $PROJECT --global --source redirect.yaml --quiet
    gcloud compute target-http-proxies create app-http-proxy --project $PROJECT --url-map app-redirect
    gcloud compute forwarding-rules create app-http --project $PROJECT --global --address app-ip --target-http-proxy app-http-proxy \
      --ports 80 --load-balancing-scheme EXTERNAL_MANAGED
    
    # 6. Point DNS at the address and wait for the certificate to become ACTIVE. Later, the logs explain every 5xx: statusDetails says why.
    IP=$(gcloud compute addresses describe app-ip --project $PROJECT --global --format="value(address)")
    echo "Create an A record: $DOMAIN -> $IP"
    gcloud compute ssl-certificates describe app-cert --project $PROJECT --global --format="value(managed.status)"
    gcloud logging read 'resource.type="http_load_balancer" AND httpRequest.status>=500' --project $PROJECT --limit 5 --freshness 1h \
      --format="table(timestamp,httpRequest.status,jsonPayload.statusDetails)"
    # Placeholders: pass in your own values. The ones below are examples.
    variable "project" {
      type = string
    }
    
    variable "region" {
      type    = string
      default = "asia-south1"
    }
    
    variable "cloud_run_service" {
      type    = string
      default = "hello"
    }
    
    variable "domain" {
      type    = string
      default = "app.example.com"
    }
    
    provider "google" {
      project = var.project
      region  = var.region
    }
    
    # A serverless network endpoint group that points at an existing Cloud Run service.
    resource "google_compute_region_network_endpoint_group" "hello" {
      name                  = "hello-neg"
      region                = var.region
      network_endpoint_type = "SERVERLESS"
    
      cloud_run {
        service = var.cloud_run_service
      }
    }
    
    # Cloud Armor: slow any client that sends more than 100 requests a minute.
    resource "google_compute_security_policy" "edge" {
      name        = "edge-policy"
      description = "Rate limit per client"
    
      rule {
        action   = "throttle"
        priority = 1000
    
        match {
          versioned_expr = "SRC_IPS_V1"
    
          config {
            src_ip_ranges = ["*"]
          }
        }
    
        rate_limit_options {
          conform_action = "allow"
          exceed_action  = "deny(429)"
          enforce_on_key = "IP"
    
          rate_limit_threshold {
            count        = 100
            interval_sec = 60
          }
        }
      }
    
      rule {
        action   = "allow"
        priority = 2147483647
    
        match {
          versioned_expr = "SRC_IPS_V1"
    
          config {
            src_ip_ranges = ["*"]
          }
        }
      }
    }
    
    resource "google_compute_backend_service" "hello" {
      name                  = "hello-backend"
      load_balancing_scheme = "EXTERNAL_MANAGED"
      protocol              = "HTTPS"
      security_policy       = google_compute_security_policy.edge.id
    
      backend {
        group = google_compute_region_network_endpoint_group.hello.id
      }
    
      log_config {
        enable      = true
        sample_rate = 1.0
      }
    }
    
    resource "google_compute_global_address" "app" {
      name = "app-ip"
    }
    
    resource "google_compute_url_map" "app" {
      name            = "app-map"
      default_service = google_compute_backend_service.hello.id
    }
    
    resource "google_compute_managed_ssl_certificate" "app" {
      name = "app-cert"
    
      managed {
        domains = [var.domain]
      }
    }
    
    resource "google_compute_target_https_proxy" "app" {
      name             = "app-proxy"
      url_map          = google_compute_url_map.app.id
      ssl_certificates = [google_compute_managed_ssl_certificate.app.id]
    }
    
    resource "google_compute_global_forwarding_rule" "https" {
      name                  = "app-https"
      target                = google_compute_target_https_proxy.app.id
      ip_address            = google_compute_global_address.app.address
      port_range            = "443"
      load_balancing_scheme = "EXTERNAL_MANAGED"
    }
    
    # A second front end on port 80 that only redirects to HTTPS, on the same address.
    resource "google_compute_url_map" "redirect" {
      name = "app-redirect"
    
      default_url_redirect {
        https_redirect         = true
        redirect_response_code = "MOVED_PERMANENTLY_DEFAULT"
        strip_query            = false
      }
    }
    
    resource "google_compute_target_http_proxy" "redirect" {
      name    = "app-http-proxy"
      url_map = google_compute_url_map.redirect.id
    }
    
    resource "google_compute_global_forwarding_rule" "http" {
      name                  = "app-http"
      target                = google_compute_target_http_proxy.redirect.id
      ip_address            = google_compute_global_address.app.address
      port_range            = "80"
      load_balancing_scheme = "EXTERNAL_MANAGED"
    }
    
    output "address" {
      value = google_compute_global_address.app.address
    }
    # pip install google-cloud-logging
    # Counts the load balancer's 5xx responses of the last hour by status code and by the reason the load balancer logged (statusDetails).
    import collections
    import datetime as dt
    
    from google.cloud import logging as cloud_logging
    
    client = cloud_logging.Client()
    
    # Some of the reasons you will meet, and what they point at:
    #   response_sent_by_backend                  the application itself answered with a 5xx
    #   backend_timeout                           the backend didn't answer within the backend service timeout
    #   failed_to_connect_to_backend              the load balancer couldn't open a connection (health, firewall or the service is down)
    #   denied_by_security_policy                 a Cloud Armor rule blocked the request
    #   client_disconnected_before_any_response   the client gave up first, which isn't a server fault
    
    
    def error_report(minutes=60, limit=1000):
        """Returns a Counter of (HTTP status, statusDetails) for recent errors, most common first when you call .most_common()."""
        since = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=minutes)).strftime("%Y-%m-%dT%H:%M:%SZ")
        log_filter = 'resource.type="http_load_balancer" AND httpRequest.status>=500 AND timestamp>="%s"' % since
        counts = collections.Counter()
        for entry in client.list_entries(filter_=log_filter, order_by=cloud_logging.DESCENDING, max_results=limit):
            payload = entry.payload if isinstance(entry.payload, dict) else {}
            status = (entry.http_request or {}).get("status")
            counts[(status, payload.get("statusDetails", "unknown"))] += 1
        return counts
    
    
    if __name__ == "__main__":
        for (status, details), count in error_report().most_common(10):
            print("%5d  HTTP %s  %s" % (count, status, details))
    // dotnet add package Google.Cloud.Compute.V1
    // Audits the project's load balancers: external backend services without a Cloud Armor policy or without request logging,
    // and HTTP proxies whose URL map serves content on port 80 instead of redirecting to HTTPS.
    using Google.Cloud.Compute.V1;
    
    string project = Environment.GetEnvironmentVariable("GOOGLE_CLOUD_PROJECT") ?? throw new InvalidOperationException("Set GOOGLE_CLOUD_PROJECT first.");
    int problems = 0;
    
    BackendServicesClient services = BackendServicesClient.Create();
    foreach (BackendService service in services.List(project))
    {
        bool external = service.LoadBalancingScheme.StartsWith("EXTERNAL");
        if (external && string.IsNullOrEmpty(service.SecurityPolicy))
        {
            Console.WriteLine($"backend service {service.Name}: no Cloud Armor policy is attached");
            problems++;
        }
        if (service.LogConfig == null || !service.LogConfig.Enable)
        {
            Console.WriteLine($"backend service {service.Name}: request logging is off");
            problems++;
        }
    }
    
    TargetHttpProxiesClient proxies = TargetHttpProxiesClient.Create();
    UrlMapsClient maps = UrlMapsClient.Create();
    foreach (TargetHttpProxy proxy in proxies.List(project))
    {
        string mapName = proxy.UrlMap.Split('/').Last();
        UrlMap map = maps.Get(project, mapName);
        if (map.DefaultUrlRedirect == null)
        {
            Console.WriteLine($"HTTP proxy {proxy.Name}: URL map {mapName} serves content over plain HTTP instead of redirecting to HTTPS");
            problems++;
        }
    }
    
    Console.WriteLine(problems == 0 ? "No problems found." : $"{problems} problem(s) found.");
    return problems == 0 ? 0 : 1;

    Best videos to explore

    Videos picked for this service. Each one is labelled with its source, opens on YouTube if you prefer, and loads only when you press play.

    Cloud Load Balancing Deep Dive and Best Practices (Cloud Next '18)Official · Google Cloud · Advanced · Watch on YouTube
    Cloud OnAir: Networking 104 - Everything You Need to Know About Load Balancers on GCPOfficial · Google Cloud · Intermediate · Watch on YouTube
    GCP Tutorial: Internal Network Load Balancer Configuration (Full Guide)Community video · Intermediate · Watch on YouTube
    Google Cloud Networking Deep DiveCommunity video · Advanced · Watch on YouTube

    Interview questions

    BasicWhat is Cloud Load Balancing?

    It’s Google Cloud’s managed load balancing service. It spreads incoming traffic over backends such as instance groups, containers and serverless services, checks their health and routes around failures. Most variants are software-defined, so there are no load balancer machines for you to size or patch.

    BasicWhat is the difference between Application and Network Load Balancers?

    Application Load Balancers work at layer 7 on HTTP and HTTPS, so they can route by host and path, redirect, rewrite and use Cloud Armor. Network Load Balancers work at layer 4 on TCP and UDP. Proxy Network Load Balancers terminate the connection, while passthrough ones forward packets and keep the client’s address.

    BasicWhat is a global external load balancer?

    It is an external load balancer with one anycast IP address that is advertised from Google’s edge locations worldwide. Visitors connect at the nearest edge, and traffic is carried over Google’s network to the closest backend with capacity, in any region. It needs the Premium Network Service Tier.

    IntermediateWhat are the parts of an external Application Load Balancer, and how do they connect?

    A forwarding rule owns the IP address and port. It points to a target proxy, which terminates TLS with a certificate and uses a URL map. The URL map sends each request to a backend service or backend bucket, and the backend service holds the backends, the health check and settings such as timeout, logging and the Cloud Armor policy.

    IntermediateWhy do all backends look unhealthy after setting up a load balancer?

    Most often the firewall blocks Google’s health check probes. Allow 130.211.0.0/22 and 35.191.0.0/16 to the backend port, and for regional Envoy-based load balancers the proxy-only subnet as well. Then check the health check’s path, port and protocol against what the service answers.

    IntermediateHow would you put a Cloud Run service behind a load balancer, and why?

    Create a serverless network endpoint group that points at the service, add it to a backend service, and build the front end with a URL map, certificate, proxy and forwarding rule. This gives the service a custom domain, Cloud Armor protection, Cloud CDN, traffic splitting and a single global address, none of which the default run.app URL offers.

    AdvancedHow do you run a canary release with a load balancer?

    Put the new version behind a second backend, for example a Cloud Run revision tagged through its own NEG, and use weighted backend services in the URL map, such as 95 to 5. Watch error rate and latency per backend in the logs and metrics, move the weights in steps, and set the weights back to roll back. The change is configuration only, so it is quick and reversible.

    AdvancedExplain the 502 and 504 errors you may see, and how the log helps.

    The load balancer logs a statusDetails value with each response. failed_to_connect_to_backend points at firewall, listener or health problems, backend_timeout at slow backends compared with the backend service timeout, and backend_connection_closed_before_data_sent_to_client at keep-alive mismatches. denied_by_security_policy shows Cloud Armor blocked the request. Filter logs by these values to find the cause quickly.

    AdvancedHow do you choose between the Premium and Standard Network Service Tiers, and between global and regional?

    Premium carries traffic across Google’s own network and is required for global external load balancers, which give one address and cross-region failover. Standard hands traffic to the internet earlier at a lower egress price and exists only for regional external load balancers. Choose global and Premium for users spread across the world, and regional and Standard for single-region workloads where cost matters more than the last bit of latency.

    AdvancedHow would you protect a public service behind Cloud Load Balancing?

    Attach a Cloud Armor policy with rate limiting and managed WAF rules, tested in preview mode first, and use Google-managed certificates with a modern SSL policy and an HTTP-to-HTTPS redirect. Keep backends private, allowing only Google’s health check ranges and the load balancer, enable request logging, alert on 4xx and 5xx spikes and review IAM so that few people can change URL maps and policies.

    Similar or alternative services on other clouds

    CapabilityAWSAzureGoogle Cloud
    ServiceElastic Load BalancingAzure Load Balancer and Azure Application GatewayCloud Load Balancing
    HTTP(S), layer 7Application Load BalancerAzure Application Gateway (a separate service)Application Load Balancers
    TCP and UDP, layer 4Network Load BalancerAzure Load Balancer (Standard)Network Load Balancers, proxy and passthrough
    Network appliancesGateway Load BalancerGateway Load Balancer SKUInternal passthrough load balancer as a next hop
    ScopeRegional load balancers, global with Route 53 or Global AcceleratorRegional, with a cross-region tierGlobal with one anycast address, or regional
    Health checksPer target groupHealth probesHealth checks on backend services
    CertificatesACM on the listenerApplication Gateway certificates, Key VaultGoogle-managed or your own
    Web firewallAWS WAF on the Application Load BalancerWAF on Application GatewayCloud Armor
    How you are billedHours plus capacity units, plus IPv4 addressesRules and data processedForwarding rule hours plus data processed

    Typical backends are Cloud Run services, Compute Engine instance groups and Google Kubernetes Engine workloads, with Cloud CDN switched on for cacheable content. Logs and metrics go to Cloud Monitoring.

    Did you find this article helpful?

    Your answer helps us improve this page for the next reader.

    Sources and further reading

    CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.