Choosing between a Layer 4 Passthrough Network Load Balancer and a Layer 7 Proxy Application Load Balancer on Google Cloud isn't just a routing or performance decision—it fundamentally changes your VPC firewall perimeter and attack surface.

Misunderstanding how traffic reaches backend VMs is one of the most common sources of both accidental 0.0.0.0/0 exposure and stubborn HTTP 502 outages. In this write-up, I compare both external Compute Engine load balancing architectures side by side using modular Terraform inside a single VPC.

TL;DR

  • What I built: A reusable Terraform repository with two isolated modules (modules/network_lb and modules/http_lb) provisioning a Regional L4 External Passthrough Network LB and a Global L7 External HTTP LB side by side on GCP.
  • Core security control: Contrasting open client ingress (0.0.0.0/0 → network-lb-tag) required for L4 passthrough against locked-down GFE proxy-only ingress (130.211.0.0/22 and 35.191.0.0/16 → allow-health-check) enabled by L7 edge termination.
  • Key takeaway: L7 proxying through Google Front Ends (GFEs) lets you block arbitrary direct internet ingress to your backend VMs at the VPC firewall layer—while L4 passthrough requires careful exposure management because the original client packet arrives untouched.

GitHub logo adrianjadev / gcp-compute-load-balancing-iac

Modular Terraform (HCL) comparing GCP Regional L4 Passthrough Network LB and Global L7 Proxy HTTP LB with defense-in-depth VPC firewall rules.

GCP Compute Engine Load Balancing — Declarative Terraform IaC (GSP313)

A modular, reusable Terraform implementation of Google Cloud's Implement Load Balancing on Compute Engine: Challenge Lab (GSP313). This repository provisions and contrasts both major external Compute Engine load balancing architectures side by side in a single VPC:

  1. Regional Layer 4 External Passthrough Network Load Balancer (modules/network_lb) — distributes raw TCP:80 traffic across three standalone Debian 12 Apache VMs (web1, web2, web3) using a Target Pool (www-pool) and a regional static external IP (network-lb-ip-1).
  2. Global Layer 7 External HTTP Application Load Balancer (modules/http_lb) — terminates HTTP at Google Front End (GFE) edge proxies (http-lb-proxy), routes through a URL Map (web-map-http) and Backend Service (web-backend-service), and serves traffic from a Managed Instance Group (lb-backend-group) protected by strict Google health-check/proxy firewall rules…

👉 Full repository: github.com/adrianjadev/gcp-compute-load-balancing-iac

1. The Problem: Why This Matters in Production

When exposing web or TCP workloads on Google Cloud, teams often copy-paste firewall rules across different load balancer types without realizing how GCP's underlying packet path behaves. That leads to two opposite failure modes:

  1. Over-permissive L7 backends: Teams attach a 0.0.0.0/0 port 80 ingress rule to Managed Instance Group (MIG) backends behind an HTTP Load Balancer. This allows attackers to bypass edge controls (such as WAF/Cloud Armor or TLS termination) and hit backend VMs directly over the internet.
  2. Broken health checks and 502 errors: Conversely, locking down an L7 backend without explicitly permitting Google's documented health-checker and GFE proxy CIDR blocks (130.211.0.0/22 and 35.191.0.0/16) leaves every backend marked UNHEALTHY—or using modern regional health checks on a Target Pool-based L4 Network LB fails at provisioning time.

Engineering objective: Model both load balancer architectures declaratively in Terraform (>= 1.6, hashicorp/google ~> 6.0) with clean module boundaries, explicit API dependency ordering, least-privilege firewall scoping per architecture, and a standalone runtime verification script.

2. Architecture & Design

Both load balancers are provisioned inside the same VPC network (default by default, parameterized via network_name) in us-west1 / us-west1-b, but their data-plane paths and trust boundaries are completely different:

Animated GCP L4 vs L7 Load Balancing Packet Flow

How Packet Flow Differs Under the Hood

  1. Path A — Regional L4 External Passthrough Network LB (modules/network_lb):
    • www-rule (:80/TCP) backed by static regional IP network-lb-ip-1 does not terminate TCP connections.
    • Google's Maglev load balancers hash packet 5-tuples to pick a healthy VM (web1, web2, or web3) in www-pool and forward the original IP packet with the client's source IP preserved and the VIP (network-lb-ip-1) as the destination IP.
    • Google's Andromeda SDN programs a local route for the VIP on the guest OS so each VM replies directly to the client. Because packets arrive with the original client source IP, www-firewall-network-lb must permit 0.0.0.0/0 (or the intended client CIDRs) on TCP 80.
  2. Path B — Global L7 External HTTP Application LB (modules/http_lb):
    • http-content-rule advertises the global Anycast IP lb-ipv4-1 from Google Front End (GFE) edge PoPs worldwide.
    • Client HTTP/TCP connections terminate at the nearest GFE, which evaluates http-lb-proxy → web-map-http → web-backend-service (targeting named port http: 80).
    • The GFE opens a new backend connection to instances in lb-backend-group (MIG) sourced strictly from Google's proxy/prober ranges (130.211.0.0/22 and 35.191.0.0/16). This allows fw-allow-health-check to reject all direct internet traffic to port 80 on the MIG VMs.

Component Breakdown

Component Cloud Service / Terraform Resource Security & Architectural Purpose
API Bootstrap google_project_service.compute_api (compute.googleapis.com) Prevents 403 Service Not Enabled race conditions in fresh GCP projects via explicit depends_on edges.
L4 Perimeter Firewall www-firewall-network-lb (network-lb-tag) Scopes TCP:80 ingress strictly to the tagged L4 backend VMs (web1–web3) via nlb_allowed_source_ranges.
L4 Target Pool & Legacy Probe www-pool + basic-check (google_compute_http_health_check) Satisfies GCP's requirement that Target Pool Network LBs use legacy HTTP health checks.
L7 Perimeter Firewall fw-allow-health-check (allow-health-check) Restricts MIG ingress solely to 130.211.0.0/22 and 35.191.0.0/16, blocking direct internet bypasses.
L7 Proxy Chain lb-ipv4-1 → http-content-rule → http-lb-proxy → web-map-http → web-backend-service Terminates HTTP at Google's global edge and decouples backend routing from raw instance ports via named port http (80).
Managed Backend Fleet lb-backend-template → lb-backend-group (e2-medium, target size 2) Provides repeatable, template-driven debian-12 Apache backends instead of manually managed standalone VMs.

3. Security Controls & Implementation Deep Dive

Control 1: Enforcing GFE-Only Ingress on L7 Backends

The single biggest network security advantage of the L7 HTTP Load Balancer is that backend instances never need to accept direct HTTP traffic from 0.0.0.0/0. By binding fw-allow-health-check strictly to Google's GFE proxy and health-prober CIDRs—and targeting only instances tagged allow-health-check—direct internet scans against MIG port 80 are dropped at the VPC firewall.

resource "google_compute_firewall" "allow_health_check" { name = "fw-allow-health-check" network = var.network_name allow { protocol = "tcp" ports = ["80"] } # Restrict ingress strictly to Google Front End (GFE) proxies & health checkers source_ranges = var.health_check_source_ranges # ["130.211.0.0/22", "35.191.0.0/16"] target_tags = [var.http_lb_target_tag] # ["allow-health-check"] } 

Control 2: Decoupling L7 Backends via Named Ports & Immutable Templates

Rather than hardcoding port 80 inside the Backend Service, lb-backend-group publishes a named_port (http → 80) that web-backend-service references via port_name = "http". Pairing this with an immutable google_compute_instance_template (lb-backend-template) ensures every scaled instance boots from the same hardened Debian 12 configuration instead of drifting like standalone VMs (web1, web2, web3).

resource "google_compute_instance_group_manager" "mig" { name = "lb-backend-group" base_instance_name = "lb-backend-group" zone = var.zone target_size = var.http_lb_mig_target_size # default: 2 version { instance_template = google_compute_instance_template.backend.id } named_port { name = "http" port = 80 } } 

Control 3: Explicit API Enablement & Parameterized Hygiene

Before Terraform reads data sources (default VPC or debian-12 OS images), the root module enables compute.googleapis.com via google_project_service.compute_api with explicit depends_on edges. All environment-specific values (project_id, region, zone, CIDRs, machine types, and labels) are parameterized in variables.tf with a safe terraform.tfvars.example template, while .gitignore excludes terraform.tfvars, *.tfstate*, *.json keys, and .env files.

Verification & Testing

Because Global HTTP Load Balancer edge propagation and VM Apache startup scripts take 3–5 minutes after terraform apply, runtime validation is intentionally kept out of fragile Terraform local-exec provisioners and placed in a dedicated verification script:

# 1. Authenticate & configure local variables gcloud auth application-default login cp terraform.tfvars.example terraform.tfvars # 2. Format, validate, and apply terraform init terraform fmt -check -recursive terraform validate terraform plan -out=tfplan terraform apply tfplan # 3. Wait 3–5 minutes for GFE propagation, then verify both load balancers chmod +x scripts/verify_load_balancers.sh ./scripts/verify_load_balancers.sh 

Expected runtime checks from scripts/verify_load_balancers.sh:

  • L4 Network LB (network-lb-ip-1): Alternating responses across <h3>Web Server: web1</h3>, web2, and web3.
  • L7 HTTP LB (lb-ipv4-1): Responses from MIG backends such as Page served from: lb-backend-group-xxxx.

4. Lessons Learned & Production Hardening

Key Engineering Takeaways

  1. Target Pool Health Check Compatibility: Target Pool-based External Network LBs reject modern regional/global google_compute_health_check resources and strictly require legacy HTTP health checks (google_compute_http_health_check — basic-check). Knowing this constraint upfront prevents frustrating API errors during terraform apply.
  2. GFE Edge Propagation Delays Are Normal: Getting transient 502 Bad Gateway or Connection Refused errors immediately after Terraform finishes does not necessarily mean your firewall is broken—GFE edge programming plus VM startup scripts routinely take 3–5 minutes to converge.
  3. Instance Template Immutability: Updating a startup script or machine type on an exact-named template (lb-backend-template) fails while referenced by a MIG. For zero-downtime rolling updates in production, switch name to name_prefix = "lb-backend-template-" and add lifecycle { create_before_destroy = true }.
  4. Heredoc Variable Escaping in Terraform: Inside a Terraform <<-EOT VM startup script, ${vm_hostname} gets interpolated by Terraform rather than Bash unless escaped as $${vm_hostname} so the guest OS evaluates the hostname at boot time.

Taking This Further in Production

This repository intentionally isolates and contrasts L4 vs. L7 HTTP load balancing fundamentals. Before deploying this pattern into a production workload, I would harden it with:

  • End-to-End TLS & WAF Protection: Replace plain HTTP on the Global LB with HTTPS (google_compute_managed_ssl_certificate + google_compute_target_https_proxy) and attach Cloud Armor security policies at the edge for DDoS and OWASP Top 10 filtering.
  • Zero Public IPs on Backend VMs: Remove ephemeral external IPs from all backend instances and route outbound OS/package updates through Cloud NAT, eliminating direct internet reachability altogether.
  • Service-Account-Scoped Firewalls: Replace mutable network tags (network-lb-tag, allow-health-check) with target service accounts so firewall membership is enforced by IAM rather than instance metadata tags.
  • DevSecOps CI/CD & Remote State: Move state to a versioned GCS remote backend and enforce automated terraform fmt, validate, Trivy/Checkov IaC scanning, and Gitleaks in GitHub Actions authenticated via Workload Identity Federation (OIDC).

Explore the Code

Inspect both Terraform modules (modules/network_lb, modules/http_lb), input/output tables, the animated packet-flow generator, and the verification script on GitHub:

When designing GCP ingress architectures, where do you draw the line between Passthrough L4 Network Load Balancing and Proxy L7 Application Load Balancing? Let's discuss in the comments!