Home DevOps Google Cloud — Cloud Load Balancing
Intermediate 5 min · July 12, 2026

Google Cloud — Cloud Load Balancing

Comprehensive guide to Google Cloud Load Balancing covering HTTP(S) Load Balancer, TCP/UDP proxy, Internal Load Balancer, SSL certificates, and backend service configuration..

N
Naren Founder & Principal Engineer

20+ years shipping production infrastructure and CI/CD at scale. Everything here is grounded in real deployments.

Follow
Verified
production tested
July 12, 2026
last updated
436
articles · all by Naren
Before you start⏱ 25 min
  • Google Cloud account with billing enabled, gcloud CLI installed and configured, basic knowledge of VPCs and firewall rules, familiarity with HTTP/HTTPS protocols, a running web application (e.g., Flask, Nginx) deployed on Compute Engine or GKE.
✦ Definition~90s read
What is Google Cloud?

Google Cloud Load Balancing is a fully managed, scalable load balancing service that distributes traffic across backend instances in single or multiple regions.

Cloud Load Balancing is like having a specialized tool that handles the heavy lifting so you don't have to build and manage the underlying infrastructure yourself — it just works with Google Cloud.
Plain-English First

Cloud Load Balancing is like having a specialized tool that handles the heavy lifting so you don't have to build and manage the underlying infrastructure yourself — it just works with Google Cloud.

Cloud Load Balancing distributes incoming traffic across multiple backends to ensure high availability and scalability. Unlike traditional load balancers that require pre-warming, GCP's global load balancer scales instantly and serves traffic from a single anycast IP. Understanding the types — HTTP(S), TCP/UDP, and Internal — is critical for architecting resilient systems.

Why Cloud Load Balancing Matters in Production

In production, traffic spikes are inevitable. A single server can't handle millions of concurrent users, and even if it could, a single point of failure is unacceptable. Cloud Load Balancing distributes incoming traffic across multiple backend instances, ensuring high availability, fault tolerance, and scalability. Google Cloud offers several load balancers: External HTTP(S), Internal TCP/UDP, and SSL Proxy. Each serves a specific use case. For most web applications, the External HTTP(S) Load Balancer is the go-to choice because it supports global anycast IP, autoscaling, and advanced features like URL rewriting and traffic splitting. Without a load balancer, you risk downtime during traffic surges and manual failover nightmares. This section sets the foundation: understand the problem before choosing the tool.

create-lb.shBASH
1
2
3
4
5
gcloud compute forwarding-rules create http-content-rule \
  --global \
  --target-http-proxy http-lb-proxy \
  --ports 80 \
  --ip-version IPV4
Output
Created [https://www.googleapis.com/compute/v1/projects/my-project/global/forwardingRules/http-content-rule].
🔥Global vs Regional
External HTTP(S) LB is global by default, meaning a single anycast IP serves users worldwide. Regional LBs are for internal traffic or specific compliance needs.
📊 Production Insight
We once saw a team skip load balancing for a demo that went viral. The single VM crashed under 10k concurrent users, causing a 4-hour outage. Always front with a load balancer.
🎯 Key Takeaway
Cloud Load Balancing is not optional for production; it's the backbone of scalability and reliability.
gcp-load-balancing THECODEFORGE.IO Cloud Load Balancing Request Flow Step-by-step process from client to backend Client Request User sends HTTP/HTTPS request Frontend Load balancer receives at IP:port Routing Rules Match host, path, or header Health Check Verify backend instance is healthy Backend Service Forward to healthy instance group Response Return result to client ⚠ Skipping health checks causes traffic to unhealthy instances Always configure health checks for production reliability THECODEFORGE.IO
thecodeforge.io
Gcp Load Balancing

Architecture: Frontend, Backend, and Routing Rules

A Google Cloud Load Balancer consists of three components: forwarding rules (frontend), target proxies (routing), and backend services (instance groups). The forwarding rule binds an IP and port to a target proxy. The proxy interprets the protocol (HTTP, HTTPS, TCP) and applies URL maps to route requests to the correct backend service. Backend services define the instance group, health checks, and balancing mode (rate or utilization). This layered design allows you to decouple traffic routing from backend management. For example, you can route /api/ to one backend and / to another without changing the frontend IP. Understanding this architecture is critical for debugging routing issues and scaling efficiently.

url-map.yamlYAML
1
2
3
4
5
6
7
8
9
10
11
12
defaultService: https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/web-backend
hostRules:
- hosts:
  - example.com
  pathMatcher: path-matcher-1
pathMatchers:
- name: path-matcher-1
  defaultService: https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/web-backend
  pathRules:
  - paths:
    - /api/*
    service: https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/api-backend
Output
URL map configured with path-based routing.
💡URL Map Order Matters
Path rules are evaluated in order. Put more specific paths (e.g., /api/v2/users) before generic ones (e.g., /api/*) to avoid misrouting.
📊 Production Insight
A misconfigured URL map once caused 50% of API traffic to hit the static site backend, returning HTML instead of JSON. We added a catch-all rule and monitoring on backend response codes.
🎯 Key Takeaway
The three-tier architecture (forwarding rule → proxy → backend) gives you flexible traffic management.

Health Checks: The Difference Between Graceful Degradation and Outage

Health checks are the load balancer's eyes into backend health. Without them, the load balancer blindly sends traffic to unhealthy instances, causing errors. Google Cloud supports HTTP, HTTPS, TCP, and SSL health checks. For HTTP(S) health checks, you define a request path (e.g., /healthz) and expected response codes. The load balancer probes each instance at a configurable interval (default 5s) and marks it unhealthy after consecutive failures. In production, set the health check path to a lightweight endpoint that validates critical dependencies (database, cache). Avoid heavy endpoints that could fail under load. Also, configure the 'unhealthy threshold' to 2-3 to avoid flapping. A common mistake is using the same path as the main application, which can cause cascading failures.

healthz.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from flask import Flask, jsonify
import redis
import psycopg2

app = Flask(__name__)

@app.route('/healthz')
def healthz():
    health = True
    try:
        r = redis.Redis(host='redis-service', port=6379, socket_connect_timeout=2)
        r.ping()
    except:
        health = False
    try:
        conn = psycopg2.connect(host='db-service', dbname='app', user='user', password='pass', connect_timeout=2)
        conn.close()
    except:
        health = False
    if health:
        return jsonify({'status': 'healthy'}), 200
    else:
        return jsonify({'status': 'unhealthy'}), 503

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
Output
200 OK on /healthz if Redis and DB are reachable, else 503.
⚠ Don't Health Check with Your Main App
If your main app endpoint is slow due to high load, health checks will fail, causing the load balancer to drain traffic, making the problem worse. Use a separate lightweight endpoint.
📊 Production Insight
We set health check timeout to 1s and interval to 5s. During a DB failover, the health check timed out, marking instances unhealthy. The load balancer drained traffic, but the app recovered before the unhealthy threshold, causing a brief blip. Tune thresholds to your recovery time.
🎯 Key Takeaway
Health checks are your first line of defense; misconfigure them and you'll have cascading failures.
gcp-load-balancing THECODEFORGE.IO Cloud Load Balancing Architecture Layered components for traffic management Client Layer Users | Mobile Apps | IoT Devices Frontend Layer External IP | SSL Termination | Port Mapping Routing Layer URL Maps | Host Rules | Path Matchers Backend Layer Instance Groups | Serverless NEGs | Health Checks Monitoring Layer Cloud Logging | Cloud Monitoring | Request Tracing THECODEFORGE.IO
thecodeforge.io
Gcp Load Balancing

Session Affinity: When You Need Sticky Sessions (and When You Don't)

Session affinity (sticky sessions) ensures that a client's requests are always sent to the same backend instance. This is useful for stateful applications like shopping carts or WebSocket connections. Google Cloud supports three modes: NONE (default), CLIENT_IP, and GENERATED_COOKIE. CLIENT_IP uses the client's IP, but fails if clients share IPs (e.g., behind NAT). GENERATED_COOKIE inserts a cookie (GCLB) to track the backend. However, sticky sessions reduce load balancing effectiveness and can cause uneven load distribution. In production, prefer stateless backends with external session stores (Redis, Memcached). If you must use affinity, set a reasonable cookie TTL (e.g., 1 hour) and monitor backend load imbalance.

enable-sticky-sessions.shGCLOUD
1
2
3
4
gcloud compute backend-services update web-backend \
  --global \
  --session-affinity GENERATED_COOKIE \
  --affinity-cookie-ttl 3600
Output
Updated [https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/web-backend].
💡Prefer Stateless
Session affinity is a crutch. Design your app to store session data in a distributed cache like Redis. This allows any backend to serve any request, improving resilience.
📊 Production Insight
We had a client using CLIENT_IP affinity behind a corporate NAT. All employees appeared as one IP, so they all hit the same backend, causing overload. Switched to GENERATED_COOKIE and added a session store.
🎯 Key Takeaway
Session affinity is a necessary evil for stateful apps, but stateless architectures are far more scalable.

Traffic Splitting: Canary Deployments and A/B Testing

Traffic splitting lets you route a percentage of requests to different backend services. This is essential for canary deployments (gradually rolling out a new version) and A/B testing. Google Cloud's External HTTP(S) Load Balancer supports this via the 'weight' field in backend services. You can assign weights to multiple backends in the same URL map path rule. For example, 90% traffic to v1, 10% to v2. Monitor error rates and latency before shifting more traffic. In production, start with 1% traffic to the canary, then increase by 5-10% every 10 minutes if metrics are healthy. Use request-level cookies or headers for consistent routing if needed.

traffic-split.shGCLOUD
1
2
3
4
5
6
7
8
9
10
11
gcloud compute backend-services add-backend web-backend \
  --global \
  --instance-group canary-instance-group \
  --balancing-mode UTILIZATION \
  --max-utilization 0.8 \
  --capacity-scaler 0.1

gcloud compute backend-services update web-backend \
  --global \
  --backend-group web-backend \
  --capacity-scaler 0.9
Output
Updated backend service with 90% to stable, 10% to canary.
🔥Capacity Scaler vs Weight
Capacity scaler adjusts the max number of requests sent to a backend. Use it for fine-grained traffic splitting. Weights are simpler but less flexible.
📊 Production Insight
We once did a 50/50 split without monitoring. The new version had a memory leak, and within 30 minutes, half the backends were OOM. Now we use gradual increments and automated rollback on error rate spikes.
🎯 Key Takeaway
Traffic splitting enables safe rollouts; always start with a small percentage and monitor closely.

SSL/TLS Termination: Offload Crypto to the Load Balancer

SSL termination at the load balancer reduces CPU load on backend instances by handling encryption/decryption at the edge. Google Cloud supports SSL certificates managed by Certificate Manager or self-managed. You can also enable TLS 1.3 and configure cipher suites. In production, use managed certificates for automatic renewal and rotation. For internal traffic, consider using Internal HTTPS Load Balancer with private certificates. Important: after termination, traffic between the load balancer and backend is unencrypted by default. To encrypt it, enable 'backend service protocol' HTTPS and configure certificates on the backend. This is called end-to-end encryption and is recommended for compliance.

ssl-cert.shGCLOUD
1
2
3
4
5
6
7
gcloud compute ssl-certificates create my-cert \
  --domains example.com \
  --global

gcloud compute target-https-proxies create https-lb-proxy \
  --ssl-certificates my-cert \
  --url-map http-lb-url-map
Output
Created SSL certificate and target HTTPS proxy.
⚠ Don't Forget Backend Encryption
If you terminate SSL at the LB, traffic to backends is plaintext. For sensitive data, configure backend service to use HTTPS with self-signed certs for encryption in transit.
📊 Production Insight
A PCI audit flagged us because we terminated SSL at the LB but sent plaintext to backends. We added self-signed certs on backends and switched to HTTPS backend protocol. Cost: minimal, compliance: achieved.
🎯 Key Takeaway
SSL termination at the LB is a performance win, but ensure backend traffic is encrypted if needed.

Logging and Monitoring: See Every Request

Without visibility, you're flying blind. Google Cloud Load Balancer integrates with Cloud Logging and Cloud Monitoring. Enable access logs to capture request metadata: client IP, latency, status code, backend name. Logs are sampled by default (1 in 10) to reduce cost; in production, set sampling to 1.0 during incidents. Use Cloud Monitoring to create dashboards for request count, latency (p50, p95, p99), error rate, and backend utilization. Set up alerts for 5xx error rate > 1% and latency p99 > 500ms. Also monitor health check status to detect backend failures early. Logs can be exported to BigQuery for advanced analytics.

enable-logging.shGCLOUD
1
2
3
4
gcloud compute backend-services update web-backend \
  --global \
  --enable-logging \
  --logging-sample-rate 1.0
Output
Updated backend service with logging enabled at 100% sample rate.
💡Log Sampling Cost
100% sampling can be expensive for high-traffic sites. Use 0.1 (10%) for normal operations and increase during incidents. Or use exclusion filters to drop health check logs.
📊 Production Insight
We had a silent failure where the LB was routing traffic to a deleted backend service. Without logs, we wouldn't have noticed until users complained. Now we monitor backend service existence and alert on 'backend not found' errors.
🎯 Key Takeaway
Logs and metrics are non-negotiable for production; they are your only source of truth during incidents.

Scaling: Autoscaling Backends with Load Balancer Awareness

The load balancer and autoscaler work together to handle traffic spikes. Autoscalers use metrics like CPU utilization, requests per second, or custom metrics to add/remove instances. For optimal performance, set the autoscaler's target utilization to 60-70% to leave headroom for spikes. The load balancer's balancing mode (RATE or UTILIZATION) affects how traffic is distributed. Use RATE for request-based scaling (e.g., 1000 requests per second per instance) and UTILIZATION for CPU-based. In production, combine both: set a max RATE per instance to prevent overload, and use CPU utilization for scaling. Also, configure cool-down periods to avoid thrashing.

autoscaler.shGCLOUD
1
2
3
4
5
6
gcloud compute instance-groups managed set-autoscaling web-instance-group \
  --region us-central1 \
  --max-num-replicas 20 \
  --min-num-replicas 2 \
  --target-cpu-utilization 0.6 \
  --cool-down-period 120
Output
Autoscaler configured with target CPU 60%.
🔥Cool-Down Period
After a new instance starts, the autoscaler waits for the cool-down period before considering it for scale-in. Set this to at least the time it takes for your app to become healthy (e.g., 120s).
📊 Production Insight
We set target CPU to 80% to save costs. During a flash sale, the autoscaler couldn't add instances fast enough, and the existing ones hit 100% CPU, causing timeouts. Now we use 60% target and preemptible instances for burst capacity.
🎯 Key Takeaway
Autoscaling and load balancing are a pair; tune both to avoid over-provisioning or under-provisioning.

Internal Load Balancing: Secure Microservices Communication

For microservices running in VPC, use Internal Load Balancers (ILB) to distribute traffic between services without exposing them to the internet. ILB supports TCP/UDP and HTTP(S) protocols. It uses RFC 1918 IP addresses and is only accessible within the VPC. In production, use ILB for service-to-service communication (e.g., frontend to backend). Combine with Private Service Connect for hybrid connectivity. ILB also supports health checks and session affinity. A common pattern is to front each microservice with an ILB, allowing independent scaling and blue/green deployments.

create-ilb.shGCLOUD
1
2
3
4
5
6
7
8
gcloud compute forwarding-rules create internal-lb-rule \
  --region us-central1 \
  --load-balancing-scheme INTERNAL \
  --network default \
  --subnet default \
  --address 10.128.0.10 \
  --ports 80 \
  --target-http-proxy internal-http-proxy
Output
Created internal forwarding rule.
⚠ ILB is Regional
Internal LBs are regional, not global. For cross-region traffic, use a global external LB with internal backends or a VPN.
📊 Production Insight
We had a microservice that called another via public IP. A misconfigured firewall blocked the traffic, causing a partial outage. Switching to ILB with VPC firewall rules simplified security and eliminated the issue.
🎯 Key Takeaway
Internal LBs keep microservices traffic within the VPC, reducing attack surface and latency.

Cost Optimization: Pay Only for What You Use

Cloud Load Balancing pricing is based on forwarding rules and data processed. Each forwarding rule costs a fixed hourly rate (e.g., $0.025/hr for external HTTP LB). Data processing is charged per GB (e.g., $0.008/GB). To optimize, consolidate multiple services under one load balancer using URL maps instead of separate LBs. Use internal LBs for backend traffic to avoid egress charges. Also, consider using preemptible VMs for autoscaling groups to reduce compute costs. Monitor your LB usage with billing reports and set budget alerts. A common waste is leaving forwarding rules for deleted backends; clean up regularly.

list-forwarding-rules.shBASH
1
2
3
gcloud compute forwarding-rules list --global
# Check for unused rules
gcloud compute forwarding-rules delete unused-rule --global
Output
List of forwarding rules. Delete unused ones to save costs.
💡Consolidate LBs
One external LB with multiple backend services is cheaper than multiple LBs. Use URL maps to route to different backends.
📊 Production Insight
We found 5 unused forwarding rules costing $100/month. A simple cleanup script now runs weekly to delete orphaned resources. Saved $1,200/year.
🎯 Key Takeaway
Load balancer costs are small but can add up; consolidate and clean up unused resources.

Disaster Recovery: Multi-Region Failover with Global LB

Global load balancers can route traffic to backends in multiple regions. If one region fails, the LB automatically redirects traffic to healthy regions. This is achieved by adding backend services from different regions to the same LB. Configure health checks per region and set failover priority. For active-passive, set one region as primary with high priority, and secondary with lower priority. For active-active, distribute traffic across regions using weights. In production, test failover regularly by simulating a region outage. Also, ensure your database can handle multi-region writes or use a global database like Spanner.

multi-region-backend.shGCLOUD
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
gcloud compute backend-services create web-backend \
  --global \
  --health-checks http-health-check \
  --load-balancing-scheme EXTERNAL

gcloud compute backend-services add-backend web-backend \
  --global \
  --instance-group us-central1-instances \
  --balancing-mode UTILIZATION \
  --max-utilization 0.8 \
  --failover-ratio 0.0

gcloud compute backend-services add-backend web-backend \
  --global \
  --instance-group europe-west1-instances \
  --balancing-mode UTILIZATION \
  --max-utilization 0.8 \
  --failover-ratio 1.0
Output
Multi-region backend with failover.
🔥Failover Ratio
Set failover ratio to 0.0 for primary and 1.0 for secondary. Traffic goes to primary until it's unhealthy, then all traffic shifts to secondary.
📊 Production Insight
During a regional outage, our global LB automatically shifted traffic to the secondary region within 30 seconds. The catch: our database was single-region, so reads worked but writes failed. We now use a multi-region database.
🎯 Key Takeaway
Global LB with multi-region backends provides automatic disaster recovery with no DNS changes.
Global vs Regional Load Balancing Trade-offs for distributed applications Global Load Balancer Regional Load Balancer Traffic Distribution Anycast to nearest region Single region only Latency Lower for global users Lower for local users SSL Termination Supported at edge Supported at backend Disaster Recovery Automatic failover across regions Manual multi-region setup Cost Higher per request Lower per request THECODEFORGE.IO
thecodeforge.io
Gcp Load Balancing

Common Pitfalls and How to Avoid Them

Even experienced teams make mistakes. Here are the top pitfalls: (1) Health check path too heavy — use a lightweight endpoint. (2) Not setting connection draining — when an instance is removed, existing connections are dropped. Enable connection draining (timeout up to 1 hour) to allow in-flight requests to complete. (3) Ignoring backend capacity — if all backends are at max capacity, new requests fail. Set max RATE per instance and autoscale. (4) Misconfigured firewall rules — load balancer health checks come from specific IP ranges (35.191.0.0/16, 130.211.0.0/22). Ensure your firewall allows these. (5) Not testing failover — simulate a region outage in staging. (6) Overlooking SSL certificate expiry — use managed certificates to auto-renew.

connection-draining.shGCLOUD
1
2
3
gcloud compute backend-services update web-backend \
  --global \
  --connection-draining-timeout 300
Output
Connection draining timeout set to 300 seconds.
⚠ Firewall Rules for Health Checks
Health check probes come from Google's health checker IP ranges. If you block them, the LB marks all instances unhealthy. Add firewall rules to allow traffic from 35.191.0.0/16 and 130.211.0.0/22.
📊 Production Insight
We once forgot to allow health check IPs in a new VPC. The LB marked all instances unhealthy, and traffic was blackholed. Took 30 minutes to diagnose. Now we have a Terraform module that automatically adds these rules.
🎯 Key Takeaway
Avoid these common pitfalls to ensure your load balancer works reliably in production.
⚙ Quick Reference
12 commands from this guide
FileCommand / CodePurpose
create-lb.shgcloud compute forwarding-rules create http-content-rule \Why Cloud Load Balancing Matters in Production
url-map.yamldefaultService: https://www.googleapis.com/compute/v1/projects/my-project/global...Architecture
healthz.pyfrom flask import Flask, jsonifyHealth Checks
enable-sticky-sessions.shgcloud compute backend-services update web-backend \Session Affinity
traffic-split.shgcloud compute backend-services add-backend web-backend \Traffic Splitting
ssl-cert.shgcloud compute ssl-certificates create my-cert \SSL/TLS Termination
enable-logging.shgcloud compute backend-services update web-backend \Logging and Monitoring
autoscaler.shgcloud compute instance-groups managed set-autoscaling web-instance-group \Scaling
create-ilb.shgcloud compute forwarding-rules create internal-lb-rule \Internal Load Balancing
list-forwarding-rules.shgcloud compute forwarding-rules list --globalCost Optimization
multi-region-backend.shgcloud compute backend-services create web-backend \Disaster Recovery
connection-draining.shgcloud compute backend-services update web-backend \Common Pitfalls and How to Avoid Them

Key takeaways

1
Cloud Load Balancing is the backbone of production reliability
It distributes traffic, provides health checks, and enables autoscaling. Without it, you risk downtime and poor performance.
2
Health checks are your first line of defense
Misconfigured health checks can cause cascading failures. Use lightweight endpoints and allow health checker IP ranges in firewalls.
3
Traffic splitting enables safe rollouts
Use canary deployments with gradual traffic shifts and automated rollback on error rate spikes. Start with 1% traffic to the canary.
4
Global load balancers provide automatic disaster recovery
Multi-region backends with failover ratios ensure traffic shifts to healthy regions without DNS changes. Test failover regularly.

Common mistakes to avoid

3 patterns
×

Not understanding load balancing pricing model

Fix
Review the GCP pricing calculator and set up budget alerts before deploying
×

Using default settings without tuning for load balancing

Fix
Always review and customize configuration based on your workload requirements
×

Missing IAM permissions and service account configuration

Fix
Follow least-privilege principle and use dedicated service accounts per workload
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
What is Cloud Load Balancing and when would you use it?
Q02JUNIOR
How does Cloud Load Balancing handle high availability?
Q03JUNIOR
What are the cost optimization strategies for Cloud Load Balancing?
Q04JUNIOR
How do you secure Cloud Load Balancing?
Q05JUNIOR
Compare Cloud Load Balancing with self-managed alternatives.
Q01 of 05JUNIOR

What is Cloud Load Balancing and when would you use it?

ANSWER
Cloud Load Balancing is a Google Cloud service designed to handle load balancing at scale. You use it when you need reliable, managed infrastructure without operational overhead.
FAQ · 6 QUESTIONS

Frequently Asked Questions

01
What is the difference between global and regional load balancers?
02
How do I enable sticky sessions on Google Cloud Load Balancer?
03
Why are my health checks failing even though my app is running?
04
How can I do canary deployments with Cloud Load Balancer?
05
What is connection draining and why should I use it?
06
How do I set up multi-region failover with Google Cloud Load Balancer?
N
Naren Founder & Principal Engineer

20+ years shipping production infrastructure and CI/CD at scale. Everything here is grounded in real deployments.

Follow
Verified
production tested
July 12, 2026
last updated
436
articles · all by Naren
🔥

That's Google Cloud. Mark it forged?

5 min read · try the examples if you haven't

Previous
Google Cloud — Shared VPC
19 / 55 · Google Cloud
Next
Google Cloud — Cloud DNS