Generated banner for Google Cloud Solution N Tier Serverless Web App
Generated logo for Google Cloud Solution N Tier Serverless Web App

Google Cloud Solution N Tier Serverless Web App

GoogleOfficialPublished by Google

  • Skill
  • Workflow
  • Cloud and DevOps
  • Apache-2.0
  • Low risk

From the author

Assists in designing and implementing secure n-tier serverless web applications and microservices on Google Cloud. Use when users need architecture designs, security checklists, Terraform code, or deployment guidance for multi-tier serverless apps, regional data residency / European sovereignty compliance, zero-trust private VPC networking, or Private Service Connect. Don't use for VM, GKE, or non-Google Cloud architectures.
— the description by Google

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured workflow for designing and deploying multi-tier serverless web applications using Google Cloud Run and Cloud SQL. It focuses on implementing strict network isolation, zero-trust VPC networking, and secure service-to-service communication. The skill guides users through requirements analysis, architecture design, Infrastructure as Code (Terraform) generation, and validation, ensuring adherence to specific security boundaries and network configurations.

What it does

  • Generates architecture designs for multi-tier serverless applications on Google Cloud.
  • Provides Terraform templates for secure infrastructure deployment.
  • Enforces security boundaries including VPC-internal ingress and least-privilege firewall policies.
  • Creates custom automated validation scripts to verify deployment integrity.
  • Offers step-by-step gcloud CLI commands for manual or scripted deployment.
  • Maps application components to specific Google Cloud products like Cloud Run, Cloud SQL, and Cloud Armor.

When to use it

  • When designing a multi-tier serverless web application on Google Cloud.
  • When you need to implement strict network isolation between frontend, application, and data tiers.
  • When you require Terraform code that adheres to specific security and networking best practices.
  • When you need to validate that a serverless deployment meets defined security and connectivity requirements.

Advantages

  • Provides a consistent, opinionated golden path for secure serverless architectures.
  • Reduces manual configuration errors through standardized Terraform and gcloud scripts.
  • Ensures security best practices are integrated directly into the infrastructure design.
  • Facilitates automated verification of complex multi-tier network and security configurations.

Usage examples

“Design a 3-tier serverless web app on Google Cloud using Cloud Run and Cloud SQL.”
The agent will provide a 3-tier architecture design, including the necessary security boundaries, and offer to generate the corresponding Terraform code.
“Generate Terraform code for a secure serverless application with Private Service Connect.”
The agent will output the complete Terraform HCL code block configured for Private Service Connect and secure VPC networking.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/google/google-cloud-solution-n-tier-serverless-web-app/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip google-cloud-solution-n-tier-serverless-web-app.zip -d .agents/skills

Documentation by Google

<!-- disableFinding(all) -->

<!-- mdlint off -->

Secure n-tier serverless web application with strict private application tiers

This skill guides agents through the workflow of designing and implementing a secure serverless web application with as many architectural design layers as specified by the user. It uses Cloud Run for the serverless layers and Cloud SQL for PostgreSQL as the data layer. A three-tier web application might be represented in three architectural layers: a Cloud Run presentation layer, a Cloud Run application layer, and a Cloud SQL for PostgreSQL database layer.

The architecture enforces strict physical and network isolation across all tiers (T1 to TN):

  • Tier 1 presentation tier (frontend / reverse proxy): Public-facing UI rendering/gateway service (Cloud Run). Exposes the entry point via Cloud Load Balancing and routes requests downstream to internal tiers privately via Direct VPC Egress.

  • Tier 2..N application tier (internal microservices / business logic): Private application services (Cloud Run). 100% isolated from the internet (Ingress: VPC-internal, INGRESS_TRAFFIC_INTERNAL_ONLY), reachable exclusively via upstream VPC routing (egress = "ALL_TRAFFIC" with Private Google Access on the subnet for *.run.app URLs).

  • Data tier: Private Cloud SQL for persistent data and Memorystore for Redis for caching, reachable exclusively from authorized application tiers.

Attribution

MUST READ: Before executing any gcloud, REST API, or MCP command, you MUST read and follow the instructions in Usage Attribution.

General guidance to the LLM

1. Direct Resource Map (Zero-Search File Access)

All necessary reference architectures, HCL templates, and checklists are co-located in this skill. Use exact relative paths from this skill folder:

Asset PathPurpose & Usage
assets/main.tfSingle Source of Truth for Terraform (HCL). Contains all security boundaries, Cloud Run v2 configs, PSC endpoints, DNS private zones, and firewall rules.
assets/output-template.mdStandardized Solution Architecture report markdown structure.
references/non-negotiable-architectural-rules.mdNon-negotiable security rules, audit checklist, and product mappings.
references/related-guidance.mdSupplemental deep reference (do NOT read for standard design or IaC tasks; read only if specialized edge-case troubleshooting is explicitly required).
  • No Directory Crawling: Do NOT run list_dir chains down workspace directories to discover these files.

  • No Search Thrashing on Local Files: Do NOT run code_search or find_by_name queries to look inside assets/main.tf. Read the file directly using view_file once and reuse the context.

  • No Redundant Skill Searches: Do NOT call skill_search for serverless or n-tier architecture skills while executing this skill.

2. Direct Inline Generation (No Subagent Delegation)
  • Perform all architecture compilation, Terraform drafting, gcloud command assembly, and validation script generation directly in the primary conversation.

  • Do NOT invoke subagents (invoke_subagent) to research external GitHub Terraform modules, probe environment configs, or draft reports. All required patterns are fully contained in assets/main.tf and references/.

3. One-Shot Clean Artifact Writing
  • Generate complete, fully-rendered, and valid HCL blocks and Markdown reports in a single write_to_file call.

  • Avoid leaving placeholders or malformed code fences that require multi-turn replace_file_content and grep_search patch loops.

  • No Unpopulated Placeholders: When embedding code or scripts inside architecture reports (e.g., Section 6 of assets/output-template.md), always inline the actual complete Terraform code, gcloud commands, and validation script code. Never output literal template placeholder comments (e.g., # [Paste of main.tf file contents]).

  • In-Response Direct Rendering (Mandatory): Whenever Terraform code, deployment scripts, or architecture reports are requested or generated (e.g., "provide a design and Terraform code", "generate IaC"), you MUST print the complete generated terraform ... HCL code block and full solution report directly in your chat response text, in addition to writing them to files on disk. Never output only an architectural design summary or file links when code is requested; automated evaluation frameworks (such as Yardstick) evaluate the raw response text and fail all code assertions if the terraform code block is missing from the message.

4. Technical Completeness Checklist
  • When providing a concise architecture summary or security checklist (e.g., when instructed not to generate full IaC), you MUST explicitly include the following technical specifications:

    • For regional load balancer deployments: regional proxy-only subnet purpose (REGIONAL_MANAGED_PROXY) and network parameter on regional forwarding rules.

    • Cloud SQL PostgreSQL version (POSTGRES_18), Edition (Enterprise Edition), High Availability (Regional HA), and Private Service Connect (psc_enabled = true).

    • Cloud NGFW Firewall Policies:

      • MUST configure explicit Cloud NGFW network firewall policies (google_compute_network_firewall_policy, google_compute_network_firewall_policy_association, and google_compute_network_firewall_policy_rule with enable_logging = var.enable_monitoring) rather than legacy google_compute_firewall.

      • Enforce default egress deny (0.0.0.0/0).

      • Allow frontend egress to backend / PGA VIPs.

      • Allow backend database egress explicitly permitting TCP port 443 to Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30) in addition to TCP port 5432 so the Cloud SQL Auth Proxy sidecar can query sqladmin.googleapis.com on startup for IAM certificate exchange.

Workflow

[!TIP] Optional MCP Server Integration: If your AI coding client supports the Model Context Protocol (MCP), you can connect the Google Developer Knowledge MCP Server (npx -y @google/mcp-developer-knowledge-server) to dynamically query real-time Google Cloud documentation (cloud.google.com/docs) alongside this skill's offline knowledge base (references/related-guidance.md).

The solution design and implementation workflow is divided into the following phases:

  • Phase 1: Requirements discovery and analysis: Analyze the workload's requirements, constraints, dependencies, and current state.

  • Phase 2: Solution design & IaC drafting: Build a technology stack, architecture, and deployment configuration for the workload. IMPORTANT: You should offer to generate the complete Terraform code (based on assets/main.tf and adhering to all Phase 3 specifications) alongside the solution architecture during this phase. This allows the user to immediately review and iteratively modify the code as the conversation continues. However, if the user explicitly states they do not want code, do not generate it yet.

  • Phase 3: Implementation plan & iterative refinement: Modify and refine the generated design and deployment instructions as the conversation and user feedback evolve.

  • Phase 4: Solution validation: Validate that the deployment meets the requirements of the workload.


Phase 1: Requirements discovery and analysis

To prevent multi-turn interview fatigue and maintain trajectory determinism across evaluations, adopt an opinionated 80% default golden path unless the user explicitly requests deviations:

  1. Default Golden Path Configuration (80% Baseline):

    • Architecture: Secure 3-tier serverless pipeline (frontend Cloud Run -> backend application Cloud Run -> Cloud SQL PostgreSQL).

    • Region: us-central1.

    • Database: Cloud SQL for PostgreSQL (POSTGRES_18) Enterprise Edition via Private Service Connect (psc_enabled = true).

    • Edge Protection: Global external Application Load Balancer with Cloud Armor WAF (sqli-v33-stable) and Cloud CDN (enable_cdn = true).

    • Domain & SSL Mode: If the user specifies a domain (e.g., app.mycompany.com), configure var.domain_name with a Google-managed certificate (use_self_signed_cert = false) and provide DNS A record instructions. If testing in a sandbox without a domain, enable self-signed mode (use_self_signed_cert = true) for immediate testability.

    • Networking & Security: Direct VPC Egress (ALL_TRAFFIC), run.app. Cloud DNS private zone, least-privilege Cloud NGFW egress firewall policies (TCP 5432, 443), and Cloud SQL Auth Proxy sidecar (DB_SOCKET_PATH with IAM Auth).

  2. Disambiguation Protocol (Optional Clarification Questions): If the user's initial prompt leaves requirements open-ended (and is not fast-forwarding with exact specs), do not present a multi-topic questionnaire. Only ask concise clarifying questions as needed before confirmation:

    1. Load Balancer & Residency Topology: Do you require a Global Application Load Balancer with Cloud CDN (default for worldwide users), or a Regional Application Load Balancer without CDN (for strict EU/regional data residency compliance)?

    2. Custom Domain vs. Sandbox Testing: Do you have a registered domain name to configure with a Google-managed certificate, or should we configure self-signed testing mode (use_self_signed_cert = true) for immediate sandbox testing over IP?

    3. In-Memory Caching Tier: Should we provision an optional Memorystore for Redis caching tier (Private Services Access) alongside Cloud SQL to accelerate read queries?

  3. Verify & Confirm: Present the confirmed 3-tier golden path decomposition to the user and request confirmation before proceeding to Phase 2 (or fast-forward automatically when instructed).

Phase 2: Solution design
  1. Retrieve Architectural Guidance Efficiently:

    • Architecture Design & Security Checklist Requests: Retrieve ONLY the 9 architectural security boundaries and audit checklist from references/non-negotiable-architectural-rules.md. Do NOT retrieve references/related-guidance.md or assets/main.tf when only high-level design/checklists are requested without full Terraform code.

    • Terraform Implementation Requests: Retrieve references/non-negotiable-architectural-rules.md and assets/main.tf (Single Source of Truth for exact HCL). Do NOT retrieve references/related-guidance.md unless specialized edge-case troubleshooting is explicitly required.

  2. Map components to Google Cloud products: Map your confirmed decomposition directly to Google Cloud products using these mandatory product mapping specifications:

    • Public Ingress & WAF: global or regional external Application Load Balancer (INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER), Cloud Armor (sqli-v33-stable), Cloud CDN (if global Application Load Balancer; note that Cloud CDN is NOT supported on regional Application Load Balancers). Note: When deploying a regional external Application Load Balancer, an explicit proxy-only subnet (purpose = "REGIONAL_MANAGED_PROXY") is required in the VPC and network must be specified on the regional forwarding rule.

    • Internal compute tiers (T1 to TN): Cloud Run microservices (INGRESS_TRAFFIC_INTERNAL_ONLY), Direct VPC Egress configured with egress = "ALL_TRAFFIC", Private Google Access enabled on the subnet, and a Cloud DNS Managed Private Zone (google_dns_managed_zone) for run.app. bound to vpc_network mapping *.run.app directly to Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30) when calling internal *.run.app URLs, deployed from specified/placeholder container image.

    • Private data tier: Cloud SQL for PostgreSQL (POSTGRES_18) via Private Service Connect + IAM DB Auth. If database caching was selected, add Memorystore Redis via Private Services Access. Depending on reliability requirements, specify either "Cloud SQL for PostgreSQL Enterprise edition instance" or a "Cloud SQL for PostgreSQL Enterprise Plus edition instance".

    • Secrets, Registry, & Security: Secret Manager, Artifact Registry, Cloud NGFW global/regional network firewall policies (google_compute_network_firewall_policy + google_compute_network_firewall_policy_rule explicitly permitting outbound TCP port 5432 to Cloud SQL PSC IP and TCP port 443 to Private Google Access VIPs 199.36.153.4/30, 199.36.153.8/30 on allow_backend_db_egress), and optional VPC Service Controls.

  3. Create architecture diagram: Create a clean Mermaid format architecture diagram (assets/output-template.md) illustrating the multi-tier request and data flow across entry point, public reverse proxy, private microservice compute tiers, and private database/caching endpoints.

  4. Draft solution architecture and generate Terraform & gcloud CLI code: Compile the requirements, technical decomposition, product mapping, architecture diagram, design recommendations, AND the complete Infrastructure as Code (Terraform based on assets/main.tf alongside a self-contained sequence of gcloud CLI deployment commands adhering to all Phase 3 mandatory specifications) into a single Markdown file structured strictly per the standardized Google Cloud Solution Architecture output When saving or outputting the report artifact, append an ISO 8601 UTC timestamp and ensure the filename strictly ends with the .md extension (e.g., workload_name_architecture_report-20260701T212820Z.md). Verify that all 9 security boundaries from assets/main.tf are documented cleanly in your report and all template placeholders are replaced with actual complete code blocks. In your response, provide the executive architecture overview, the 9 key security & network boundaries enforced, the complete deploy-ready Terraform code block (```terraform ... ```), and step-by-step deployment instructions with links to the generated artifacts (always inlining the complete Terraform code directly in the response when code is requested, rather than only providing file links).

  5. Request review and iterate: Present the solution architecture (and Terraform code, gcloud script, or validation script if generated) to the user and request feedback. Modify and refine both the architecture and code iteratively as the conversation continues.


Phase 3: Implementation plan
  1. Retrieve relevant building block templates from the assets/ directory. Important: Use the code in assets/main.tf as the foundation for your Terraform implementation plan (assets/output-template.md for architecture structure).

  2. Identify deployment prerequisites:

    • Required Google Cloud APIs (run.googleapis.com, sqladmin.googleapis.com, redis.googleapis.com, servicenetworking.googleapis.com, secretmanager.googleapis.com, monitoring.googleapis.com, dns.googleapis.com).

    • Required IAM permissions (Project Editor, Security Admin, etc.).

  3. Generate Infrastructure as Code (IaC) (Architectural Specifications): Retrieve relevant architectural and hierarchy guidance from references/non-negotiable-architectural-rules.md. Base code strictly on the building blocks in assets/main.tf (Section 1.5 for Cloud NGFW firewall policies, Section 5.1 for Tier 1, Section 5.2 for Tiers 2..N), ensuring database_version = "POSTGRES_18" is preserved exactly. Ensure firewall policies strictly use Cloud NGFW resources (google_compute_network_firewall_policy, google_compute_network_firewall_policy_association, and google_compute_network_firewall_policy_rule with enable_logging = var.enable_monitoring). NEVER generate legacy google_compute_firewall resources or revert to older database versions like POSTGRES_15.

  4. Write deployment instructions & README.md: Draft comprehensive step-by-step deployment instructions (or a complete README.md artifact), ensuring you include:

    • Instructions to initialize and apply Terraform (terraform init, terraform apply). Zero-Install Environment Recommendation: Explicitly recommend running terraform commands and your generated automated validation script inside Google Cloud Shell (https://shell.cloud.google.com), where python3, gcloud, and terraform are 100% pre-installed and authenticated out of the box so developers without local SDKs can deploy and validate immediately.

    • Step-by-Step gcloud CLI Deployment Commands (Bottom-Up Wiring): In Section 6.3 ("Step-by-step gcloud CLI deployment commands") inside assets/output-template.md, provide a complete, self-contained sequence of gcloud CLI commands required to deploy this exact architecture without Terraform. These commands must enforce reverse/bottom-up order (VPC/subnets -> data tiers -> internal microservices -> public gateway -> load balancer), specify --database-version=POSTGRES_18 when provisioning Cloud SQL, and extract downstream container URLs (gcloud run services describe... --format='value(status.url)') into shell variables to dynamically pass them via --update-env-vars into upstream services.

    • Explanation of all Terraform variables, explicitly including and documenting the enable_vpc_sc and use_self_signed_cert variables (explaining how setting use_self_signed_cert = true enables immediate sandbox verification via curl -k https://<LB_IP>/ without waiting for DNS propagation).

    • Dedicated VPC Service Controls Guidance Section: Provide specific instructions and gcloud commands for implementing an Org-level VPC-SC service perimeter around Cloud Run (run.googleapis.com), Cloud SQL (sqladmin.googleapis.com), and Secret Manager (secretmanager.googleapis.com) when enable_vpc_sc = true.

    • Container image deployment strategies (specifying pre-existing image URLs or placeholder bootstrapping followed by CI/CD).

    • Cloud DNS Managed Private Zone (google_dns_managed_zone) configuration for run.app. bound to vpc_network, mapping *.run.app directly to Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30), alongside external DNS records and database schema initialization.

  5. Request review: Present the implementation plan to the user for approval. Iterate as needed.


Phase 4: Solution validation
  1. Define solution verification steps & requirements: During validation planning, mandate these 5 verification steps across any deployed environment:

    • SSL Provisioning: Verify that the Google-managed SSL certificate (google_compute_managed_ssl_certificate) becomes ACTIVE (checking --global status or regional equivalents).

    • Frontend Ingress Block: Verify that direct internet access targeting the Tier 1 Frontend's default *.run.app URL is blocked (HTTP 403 Forbidden from edge screening).

    • Backend Ingress Block: Verify that direct internet access targeting internal compute tiers' *.run.app URLs (INGRESS_TRAFFIC_INTERNAL_ONLY) is blocked across all internal microservice tiers (HTTP 404 Not Found or HTTP 403 Forbidden).

    • Frontend Public Access via Application Load Balancer: Verify that accessing the custom domain routes successfully to the presentation tier via the Application Load Balancer (HTTP 200 to 399).

    • Edge WAF Protection: Verify that a simulated SQL injection request (/?id=1%20OR%201=1 on the custom domain) is intercepted and blocked (HTTP 403 Forbidden from Cloud Armor).

    • Private Server-to-Server Connectivity: Verify via Cloud Run application logs (Logs Explorer) and database connection pooling telemetry (Cloud SQL Query Insights) that tier 1 -> tier 2 -> data tier queries succeed over private VPC fiber (Direct VPC Egress + Private Service Connect / Private Services Access).

  2. Generate tailored automated validation script: Rather than relying on a static pre-packaged script, generate a custom automated validation script (e.g., self-contained Python validation script using standard built-in urllib / subprocess libraries, or a cross-platform bash/PowerShell script) customized precisely to the user's deployed domain, SSL certificate name, and exact multi-tier *.run.app URIs.

  3. Provide cross-platform execution guidance: Explain how the user can execute the generated script across their target OS (macOS, Linux, Windows PowerShell, or zero-install Google Cloud Shell (https://shell.cloud.google.com)).

  4. Compile validation report: Document the validation checks, the generated verification script code, execution commands, and expected outcomes in Section 6.4 ("Solution verification guide and custom automated validation script") inside assets/output-template.md.

  5. Conduct validation and finalize: Assist the user in running the generated verification script, inspecting logs, and troubleshooting any DNS or WAF propagation issues. Request final approval.

Files

references/related-guidance.md

<!-- disableFinding(all) -->

<!-- mdlint off -->

Architectural reference: secure serverless three-tier web application

This document provides deep technical guidance and architectural best practices for deploying a secure, highly available, n-tier (multi-tier) serverless web application on Google Cloud.

The architecture enforces strict physical and network isolation between the tiers:

  1. Presentation tier: Public-facing UI rendering and reverse-proxy service (Cloud Run).

  2. Application tiers: Private business logic service (Cloud Run), reachable only from the VPC.

  3. Data tier (database and cache): Private persistent storage (Cloud SQL) and in-memory caching (Memorystore Redis), reachable only from the application tier.


Table of Contents

  • 1. Strict three-tier architecture overview (Lines 49–82)

  • 2. Ingress and routing: external vs. internal (Lines 84–100)

    • Presentation tier ingress (Lines 86–90)

    • Application tier ingress (Lines 91–99)

  • 3. Least-privilege network egress and Cloud NGFW firewall policies (Lines 102–111)

  • 4. Caching tier: Memorystore for Redis (optional) (Lines 113–128)

    • Redis deployment and security (Lines 119–127)

  • 5. Secure database access: Private Service Connect and Cloud SQL Auth Proxy (Lines 130–138)

  • 6. Security and operational best practices (Lines 140–157)

    • Presentation tier as a reverse proxy (Lines 142–147)

    • Secrets management (Lines 148–150)

    • Optional VPC Service Controls perimeter (Lines 151–156)

  • 7. Content delivery network (Cloud CDN) (optional) (Lines 159–169)

    • How it works and trade-offs (Lines 163–168)

  • 8. Load balancer topology: global vs. regional (Lines 171–210)

    • Comparison and trade-offs (Lines 175–185)

    • Why choose a regional Application Load Balancer? (compliance and data residency) (Lines 186–190)

    • Regional proxy-only subnet and network parameter requirements (Lines 191–195)

    • Terraform resource mapping (global to regional) (Lines 196–209)

  • 9. Observability and monitoring (optional) (Lines 212–252)

    • 9.1 VPC Flow Logs (Network Auditing) (Lines 218–223)

    • 9.2 Firewall Policy Logging (Network Access Auditing) (Lines 224–230)

    • 9.3 Load Balancer Access Logs (Application Ingress Auditing) (Lines 231–236)

    • 9.4 Cloud Monitoring Alerting Policies (Proactive Operations) (Lines 237–241)

    • 9.5 Advanced industry observability checklist (production best practices) (Lines 242–251)

  • 10. Container image storage and deployment strategy (Artifact Registry) (Lines 254–283)

    • Recommended storage: Artifact Registry (Lines 258–263)

    • Deployment strategy: pre-existing images vs. initial bootstrapping (Lines 264–279)

    • Other service patterns (Lines 280–283)


1. Strict three-tier architecture overview

In this strict model, the Application Tier is completely private and has no public internet presence. The Presentation tier acts as the gatekeeper. The user's browser only communicates with the Presentation tier, which in turn communicates with the Application tier over the private VPC network.

flowchart TD
    User["User Browser"] -->|HTTPS| APP_LB["Global external Application Load Balancer + Cloud Armor"]
    
    subgraph GoogleCloud["Google Cloud Project"]
        APP_LB --> FE_NEG["Serverless NEG - Presentation Tier"]
        FE_NEG --> FE_Run["Cloud Run - Presentation Tier"]
        
        subgraph VPC["VPC Network"]
            subgraph PUB_SUB["Public/Private Subnet"]
                FE_VPC_Interface["Frontend VPC interfaces - IPs in Subnet"]
            end
            
            subgraph PRIV_SUB["Private Subnet"]
                BE_VPC_Interface["Backend VPC interfaces - IPs in Subnet"]
                CloudSQL[(Cloud SQL PostgreSQL)]
                Redis[(Memorystore Redis)]
            end
        end
        
        FE_Run -->|Direct VPC Egress| FE_VPC_Interface
        FE_VPC_Interface -->|Private API Call via VPC Routing| BE_Run["Cloud Run - Application Tier - Application Tier (Ingress - VPC-internal)"]
        
        BE_Run -->|Direct VPC Egress| BE_VPC_Interface
        BE_VPC_Interface -->|Private Service Connect| CloudSQL
        BE_VPC_Interface -->|Private Services Access| Redis
    end

2. Ingress and routing: external vs. internal

Presentation tier ingress
  • External Entry Point: Exposed via a global external Application Load Balancer or regional external Application Load Balancer with Cloud Armor WAF protection.

  • CDN Caching: Cloud CDN is enabled on the Application Load Balancer backend service to cache static assets (HTML, JS, CSS, images) at the edge, reducing compute load on the Presentation Tier. Cloud CDN does not support the regional external Application Load Balancer and can't be used with that load balancer.

  • Ingress Bypass Protection: Ingress is restricted to internal-and-cloud-load-balancing to ensure all public traffic must pass through Cloud Armor.

Application tiers ingress
  • Greater than 3 tiers: If there are more than 3 tiers in the deployment, then there can be more than one application tier.

  • Zero Public Exposure: Ingress is set strictly to VPC-internal (INGRESS_TRAFFIC_INTERNAL_ONLY). The Application Tiers have no public URL and cannot be reached from the internet.

  • Private VPC Routing (*.run.app): Upstream services calling an internal *.run.app URL (e.g., Presentation Tier calling Application Tier) must configure the following:

    • Direct VPC Egress: Set egress = "ALL_TRAFFIC" on the calling Cloud Run service.

    • Private Google Access: Enable private_ip_google_access = true on the Cloud Run subnet.

    • Cloud NGFW Egress Rules: Configure firewall policy rules (google_compute_network_firewall_policy_rule) allowing outbound traffic to Google API VIP ranges (199.36.153.4/30, 199.36.153.8/30).

    • Cloud DNS Managed Private Zone: Deploy a private zone (google_dns_managed_zone) for run.app. bound to vpc_network that maps *.run.app directly to Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30).


3. Least-privilege network egress and Cloud NGFW firewall policies

Implement strict network-level isolation using Direct VPC Egress combined with zero-trust Cloud NGFW Global or Regional Network Firewall Policies (google_compute_network_firewall_policy and google_compute_network_firewall_policy_rule):

  • Default Egress Deny: The Cloud Run subnets enforce a default-deny egress network firewall policy rule (dest_ip_ranges = ["0.0.0.0/0"], priority 65534), ensuring serverless runtimes cannot reach unauthorized internal destinations or leak data to external IPs.

  • Presentation Tier: Enforces an explicit egress allow rule permitting the Presentation Tier service account to send traffic strictly to the Application Tier (permitting the Cloud Run subnet CIDR alongside Google API VIP ranges 199.36.153.4/30, 199.36.153.8/30 for ALL_TRAFFIC Private Google Access *.run.app routing). It is not granted access to Data tier subnets or endpoints.

  • Application Tier: Configured with egress = "PRIVATE_RANGES_ONLY", enforcing an explicit egress allow rule permitting the Backend service account to reach exclusively the local VPC Cloud SQL Private Service Connect endpoint (TCP 5432) and Memorystore Redis instance (TCP 6379).

  • Firewall Policy Logging: Each network firewall policy rule supports optional logging (enable_logging = var.enable_monitoring) to audit allowed and denied connections for security verification and compliance.


4. Caching tier: Memorystore for Redis (optional)

To reduce database load and improve API response times, the Application tier can optionally utilize Memorystore for Redis as a private caching tier.

While not a hard requirement for the application to function, it is highly recommended for production workloads.

Redis deployment and security
  • Optional Optimization: The architecture can be deployed without Redis. If omitted, the Application Tier simply queries Cloud SQL directly for all requests, reducing infrastructure costs.

  • VPC Bound: If deployed, Memorystore is provisioned with a private IP address within the VPC network.

  • Authorized Network: Access is restricted to the VPC. The Application Tier connects to the Redis instance's private IP and port (default 6379) via its Direct VPC Egress.

  • Use Cases:

    • Session State: Storing user sessions so the Application Tier remains stateless.

    • Query Caching: Caching expensive database query results.


5. Secure database access: Private Service Connect and Cloud SQL Auth Proxy

The Application tier connects to the private Cloud SQL instance via a local Private Service Connect endpoint in the consumer VPC, protected by the Cloud SQL Auth Proxy sidecar container in the Application Tier Cloud Run service.

  • Private Service Connect: Unlike legacy Private Services Access peering, Private Service Connect provisions a single internal IP endpoint directly inside the customer VPC subnet. This eliminates IP CIDR exhaustion (/16 requirements), avoids transitive peering restrictions across multi-VPC networks, and allows standard VPC egress firewall rules to restrict database connectivity.

  • IAM-based Authorization: Authorizes connections using the Backend service account's IAM identity, eliminating static passwords.

  • Mutual TLS (mTLS): Encrypts all database traffic in transit automatically.


6. Security and operational best practices

Presentation tier as a reverse proxy

By routing all API calls through the Presentation Tier server:

  1. Hidden API Structure: The internal API endpoints, schemas, and routing are completely hidden from the public internet.

  2. Centralized Authentication: The Presentation Tier can validate session cookies/tokens at the edge before forwarding requests to the Backend, protecting the Backend from unauthorized load.

  3. Simplified Domain/CORS: The browser only ever talks to one domain (the Presentation Tier). No CORS configuration is required.

Secrets management

All database credentials, Redis connection strings, and API keys are stored in Secret Manager and mounted securely as environment variables in the Application Tier service.

Optional VPC Service Controls perimeter

While Private Service Connect and VPC Egress Firewalls secure the network data plane (traffic to TCP 5432), VPC Service Controls can be optionally enabled to protect the API management plane (sqladmin.googleapis.com, secretmanager.googleapis.com, run.googleapis.com).

  • Preventing API Data Exports: Blocks API calls like sqladmin.instances.export aimed at copying database dumps to external Cloud Storage buckets outside the perimeter.

  • Preventing External Credential Abuse: Rejects API calls originating from unauthorized networks or untrusted devices even if legitimate IAM credentials are used.


7. Content delivery network (Cloud CDN) (optional)

For public-facing web applications, enabling Cloud CDN on the external Application Load Balancer is a highly effective, optional performance and cost-optimization control.

How it works and trade-offs
  • Edge Caching: Cloud CDN caches static content (images, CSS, JS, media) at Google's global network edge.

  • Cost Savings: Cloud Run charges for CPU allocation and network egress. By serving static assets from the CDN cache, you bypass Cloud Run container activations and replace expensive serverless egress with much cheaper CDN egress fees.

  • Toggling CDN: The architecture supports turning CDN on or off via the enable_cdn boolean variable in Terraform. If disabled (e.g., if you have no static assets or use a third-party CDN like Cloudflare in front of the LB), the Load Balancer forwards all requests directly to the Presentation Tier container.

  • Requirements: Cloud CDN requires a global Application Load Balancer; it is not supported on regional Application Load Balancers.


8. Load balancer topology: global vs. regional

By default, this architecture recommends a global external Application Load Balancer. However, depending on compliance, data residency, and performance requirements, you can choose to deploy a regional external Application Load Balancer.

Comparison and trade-offs
Feature / MetricGlobal external Application Load Balancer (Default)Regional external Application Load Balancer (Alternative)
Routing & EdgeAnycast IP. Traffic enters Google's network at the nearest edge PoP globally and travels over Google's backbone.Unicast IP. Traffic enters Google's network at the specific region's ingress point.
SSL TerminationTerminated at the global edge PoP closest to the user.Terminated strictly within the designated Google Cloud region.
Cloud CDNSupported. Native edge caching is available to drastically reduce Presentation Tier load and egress costs.Not Supported. Static assets must be served directly from the Presentation Tier container.
Subnet & Network RequirementsNo proxy-only subnet needed (Google Anycast edge proxies handle routing). Global forwarding rules (google_compute_global_forwarding_rule) do not require network.Requires an additional regional proxy-only subnet (google_compute_subnetwork with purpose = "REGIONAL_MANAGED_PROXY", role = "ACTIVE") for Envoy proxies, and regional forwarding rules (google_compute_forwarding_rule) must explicitly specify network.
LatencyLowest globally (Anycast routing + edge termination).Higher for users far from the destination region.
Primary Use CasesPublic-facing websites, global audiences, workloads requiring edge caching (CDN), and standard web apps.Strict compliance, data residency (e.g., GDPR, sovereign cloud where SSL keys/decryption must not leave a region), or strictly regional architectures.
Why choose a regional Application Load Balancer? (compliance and data residency)

The primary driver for choosing a regional Application Load Balancer is compliance and data sovereignty:

  • SSL Decryption Boundary: In a global Application Load Balancer, Google terminates SSL at its global edge locations. If your security policy or local regulations dictate that data must remain encrypted until it physically enters a specific geographic territory (e.g., Germany or the EU), a global Application Load Balancer cannot comply.

  • Regional Isolation: A regional Application Load Balancer ensures that all traffic processing, WAF (Cloud Armor) evaluation, and SSL decryption occur exclusively within the boundaries of the selected region.

Regional proxy-only subnet and network parameter requirements

When deploying a regional external Application Load Balancer (EXTERNAL_MANAGED), Google runs Envoy proxies internally within your target region and VPC network. Because of this architectural difference from global Anycast routing:

  1. Proxy-Only Subnet Required: You must provision an additional explicit regional proxy-only subnet (google_compute_subnetwork with purpose = "REGIONAL_MANAGED_PROXY" and role = "ACTIVE", e.g., 10.129.0.0/23) inside the VPC network (network = google_compute_network.vpc_network.id) and region alongside your Cloud Run subnet. Managed Envoy proxies use IP addresses from this proxy-only subnet when establishing connections with target backends (such as Serverless NEGs).

  2. Network Parameter on Forwarding Rule Required: When creating the regional forwarding rule (google_compute_forwarding_rule with load_balancing_scheme = "EXTERNAL_MANAGED"), you must explicitly specify the network parameter (network = google_compute_network.vpc_network.id) alongside region, ip_address, port_range, and target to bind the load balancer forwarding rule directly to your VPC network and its proxy-only subnet.

Terraform resource mapping (global to regional)

If a customer requires a regional Application Load Balancer, the Terraform resources must be swapped as follows:

Global Resource (in main.tf)Regional Equivalent ResourceKey Differences
(None - New Resource Required)google_compute_subnetwork (Proxy-Only Subnet)Must provision an additional regional proxy-only subnet (purpose = "REGIONAL_MANAGED_PROXY", role = "ACTIVE", e.g., ip_cidr_range = "10.129.0.0/23") in the target region and network of your VPC for the regional Envoy proxy pool.
google_compute_global_addressgoogle_compute_addressAdd region parameter to the regional address.
google_compute_backend_servicegoogle_compute_region_backend_serviceAdd region parameter. Note: enable_cdn is not supported on regional.
google_compute_managed_ssl_certificategoogle_compute_region_ssl_certificate (or Certificate Manager)Regional certificates must be provisioned in the specific region.
google_compute_url_mapgoogle_compute_region_url_mapAdd region parameter.
google_compute_target_https_proxygoogle_compute_region_target_https_proxyAdd region parameter.
google_compute_global_forwarding_rulegoogle_compute_forwarding_ruleAdd region parameter, set load_balancing_scheme = "EXTERNAL_MANAGED", and must explicitly specify network = google_compute_network.vpc_network.id when creating regional managed forwarding rules.

9. Observability and monitoring (optional)

To ensure operational excellence and rapid incident response, this architecture supports an optional observability tier that can be toggled on or off via a single configuration variable (enable_monitoring).

This tier implements the following distinct, high-value observability controls:

9.1 VPC Flow Logs (Network Auditing)

VPC Flow Logs record a sample of network flows sent from and received by VM interfaces and serverless VPC egress interfaces.

  • Use Cases: Network troubleshooting (e.g., verifying if tier-to-tier traffic is blocked), security forensics, and network load monitoring.

  • Default Configuration: Configured by default (enable_monitoring = true) on the Cloud Run subnet (cloud_run_subnet) with a cost-optimized capture rate of 10% (flow_sampling = 0.1) over a 1-minute aggregation interval (aggregation_interval = "INTERVAL_1_MIN").

  • Cost Trade-off & Tuning: Flow logs can generate massive volumes of data in high-traffic environments, leading to significant Cloud Logging ingestion and storage costs. You can increase flow_sampling up to 1.0 and shorten aggregation_interval if your security or diagnostics require more detailed packet flow data. Alternatively, if you do not need flow data or want zero observability ingestion costs during development, you can disable VPC Flow Logs along with other optional logging controls by setting enable_monitoring = false.

9.2 Firewall Policy Logging (Network Access Auditing)

Firewall Policy Logging records when a Cloud NGFW network firewall policy rule allows or denies traffic.

  • Captured Data: Connection 5-tuple (source/destination IP, source/destination port, protocol), action taken (ALLOW or DENY), rule name, and instance/service account metadata.

  • Use Cases: Verifying zero-trust egress policies (e.g., auditing any denied connection attempts from Cloud Run containers or verifying valid traffic to Cloud SQL and Redis), security compliance, and threat hunting.

  • Cost Trade-off: Like VPC Flow Logs, high-volume firewall logging can increase Cloud Logging ingestion volumes.

  • Toggleable: Controlled via the enable_monitoring variable by setting enable_logging = var.enable_monitoring on each network firewall policy rule.

9.3 Load Balancer Access Logs (Application Ingress Auditing)

Load Balancer access logs capture detailed metadata for every HTTP request entering your application through the global external Application Load Balancer.

  • Captured Data: Client IP, request URL, HTTP status codes, latency, Cloud CDN cache hit/miss status, and Cloud Armor WAF block decisions (showing which WAF rule triggered a block).

  • Importance: Critical for security monitoring (SIEM integration) and for verifying that Cloud Armor is correctly blocking malicious payloads.

  • Toggleable: Can be enabled/disabled on the Load Balancer's backend service.

9.4 Cloud Monitoring Alerting Policies (Proactive Operations)

Rather than waiting for users to report outages, the architecture can provision automated Alerting Policies in Cloud Monitoring.

  • Default Alert: Provisions a threshold alert on Frontend HTTP 5xx Error Rates. If the rate of server errors exceeds a set threshold (e.g., >5% of total requests over 1 minute), an alert is triggered.

  • Notification: In a production landing zone, these alerts are linked to Notification Channels (such as email, Slack, or PagerDuty) to wake up on-call engineers.

9.5 Advanced industry observability checklist (production best practices)

To establish world-class observability across multi-tier serverless pipelines (Cloud Run v2 + Cloud SQL PSC + Redis PSA + Application Load Balancer + Cloud Armor WAF), incorporate the following six practices:

  1. Distributed Tracing (Cloud Trace & OpenTelemetry): Propagate traceparent (X-Cloud-Trace-Context) HTTP headers across container tiers (T1 -> T2 -> T3 -> DB) to render complete, end-to-end request latency waterfalls inside Google Cloud Trace, eliminating guesswork when pinpointing multi-service bottlenecks.

  2. Database Deep Observability (Cloud SQL Query Insights): Enable Cloud SQL Query Insights (insights_config { query_insights_enabled = true } in Cloud SQL settings). Query Insights automatically monitors database load metrics, detects N+1 query anomalies, captures slow execution plans (SELECT * FROM...), and attributes database contention directly to specific Cloud Run application workloads.

  3. Proactive Synthetic Probing (Cloud Monitoring Uptime Checks): Configure global Uptime Checks (google_monitoring_uptime_check_config) to continuously ping your public presentation endpoint (/healthz or /) from multiple geographical checkpoints every 60 seconds. This triggers immediate incident notifications during zero-traffic windows before real users experience failures.

  4. Structured JSON Logging & Cloud Error Reporting: Emit all container logs as Structured JSON ({"severity": "ERROR", "message": "...", "trace": "..."}) rather than plain text. Cloud Logging native JSON ingestion automatically populates structured fields for instant filtering, while standard exception tracebacks (Traceback...) automatically group into Cloud Error Reporting for real-time crash tracking across container revisions.

  5. Serverless Concurrency & Cold-Start Saturation Metrics: Continuously monitor container concurrency (run.googleapis.com/container/concurrency), instance counts (container/instance_count), and latency percentiles (p95, p99). High cold-start ratios directly indicate where Minimum Instances (scaling.min_instance_count) should be provisioned on sensitive intermediate tiers (API Gateway or Auth Service).

  6. Long-Term Audit & SIEM Archival (Log Router Sinks): Because standard Cloud Logging buckets retain logs for only 30 days by default, configure an organization or project Log Router Sink (google_logging_project_sink) to continuously export high-volume audit, load balancer access logs, and VPC egress firewall logs into BigQuery (for SQL threat hunting) or Cloud Storage (Archive Storage) for multi-year regulatory compliance (SOC2, GDPR, PCI-DSS).


10. Container image storage and deployment strategy (Artifact Registry)

A critical consideration for three-tier serverless applications is where container images are securely stored and how application revisions are deployed to Cloud Run across the development lifecycle.

  • Repository Type: Store container images for both the Presentation Tier and Application Tier in Google Cloud Artifact Registry standard Docker repositories.

  • Regional Colocation: Deploy the Artifact Registry repository in the same Google Cloud region (or corresponding multi-region) as the Cloud Run services to minimize latency, eliminate inter-region data egress fees during container pulls, and comply with data residency boundaries.

  • Vulnerability Scanning: Enable automated vulnerability scanning (via Container Analysis) in Artifact Registry to scan base images and application packages for CVEs prior to deploying revisions to Cloud Run.

  • IAM Access Control: Ensure that the Cloud Run service agent (service-[PROJECT_NUMBER]@serverless-robot-prod.iam.gserviceaccount.com) or the dedicated runtime service account has roles/artifactregistry.reader permissions on the repository if images are pulled across project boundaries.

Deployment strategy: pre-existing images vs. initial bootstrapping

When provisioning core infrastructure via Terraform, choose one of two workflows based on project maturity:

  1. Pre-existing Production Images:

    • If container images have already been built and published to Artifact Registry (e.g., during migration or staging promotion), pass the full image URIs directly into Terraform:

      frontend_image = "us-central1-docker.pkg.dev/my-project/web-repo/frontend:v1.2.0"
      backend_image  = "us-central1-docker.pkg.dev/my-project/web-repo/backend-app:v1.2.0"
    • Terraform deploys the Cloud Run services immediately executing your custom application code.

  2. Decoupled Bootstrapping with Placeholder Images:

    • In new environments, infrastructure provisioning (VPC, Cloud SQL, IAM, Load Balancer) often precedes the initial application build. In this scenario, allow Terraform variables to use lightweight public placeholder images (such as us-docker.pkg.dev/cloudrun/container/hello).

    • Once Terraform completes initial infrastructure bootstrapping, automated CI/CD pipelines (such as Cloud Build, GitHub Actions, or GitLab CI) build application code, push containers to Artifact Registry, and issue gcloud run deploy commands to update container image revisions on Cloud Run.

    • Terraform State Lifecycle: Because application pipelines update container image revisions out-of-band, configure Terraform's lifecycle { ignore_changes = [template[0].containers[0].image] } block if necessary to prevent subsequent Terraform runs from reverting deployed application images back to initial placeholder values.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs network access, Needs Python, Needs Node.js

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Google
Publisher
Google (Official)
Source
google/skills · skills/cloud/google-cloud-solution-n-tier-serverless-web-app · commit 2194d3b
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google or Google.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download google-cloud-solution-n-tier-serverless-web-app.zip