Google Cloud Solution N Tier Serverless Web App
GoogleOfficialPublished by Google
- Skill
- Workflow
- Cloud and DevOps
- Apache-2.0
- Low risk
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
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/google/google-cloud-solution-n-tier-serverless-web-app/downloadUnzip 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.appURLs).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 Path | Purpose & Usage |
|---|---|
assets/main.tf | Single 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.md | Standardized Solution Architecture report markdown structure. |
references/non-negotiable-architectural-rules.md | Non-negotiable security rules, audit checklist, and product mappings. |
references/related-guidance.md | Supplemental 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_dirchains down workspace directories to discover these files.No Search Thrashing on Local Files: Do NOT run
code_searchorfind_by_namequeries to look insideassets/main.tf. Read the file directly usingview_fileonce and reuse the context.No Redundant Skill Searches: Do NOT call
skill_searchfor serverless or n-tier architecture skills while executing this skill.
2. Direct Inline Generation (No Subagent Delegation)
Perform all architecture compilation, Terraform drafting,
gcloudcommand 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 inassets/main.tfandreferences/.
3. One-Shot Clean Artifact Writing
Generate complete, fully-rendered, and valid HCL blocks and Markdown reports in a single
write_to_filecall.Avoid leaving placeholders or malformed code fences that require multi-turn
replace_file_contentandgrep_searchpatch 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 theterraformcode 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) andnetworkparameter 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, andgoogle_compute_network_firewall_policy_rulewithenable_logging = var.enable_monitoring) rather than legacygoogle_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
443to Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30) in addition to TCP port5432so the Cloud SQL Auth Proxy sidecar can querysqladmin.googleapis.comon 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.tfand 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:
Default Golden Path Configuration (
80% Baseline):Architecture: Secure 3-tier serverless pipeline (
frontendCloud Run ->backend applicationCloud 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), configurevar.domain_namewith a Google-managed certificate (use_self_signed_cert = false) and provide DNSArecord 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_PATHwith IAM Auth).
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: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)?
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?In-Memory Caching Tier: Should we provision an optional Memorystore for Redis caching tier (
Private Services Access) alongside Cloud SQL to accelerate read queries?
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
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 retrievereferences/related-guidance.mdorassets/main.tfwhen only high-level design/checklists are requested without full Terraform code.Terraform Implementation Requests: Retrieve
references/non-negotiable-architectural-rules.mdandassets/main.tf(Single Source of Truth for exact HCL). Do NOT retrievereferences/related-guidance.mdunless specialized edge-case troubleshooting is explicitly required.
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 andnetworkmust be specified on the regional forwarding rule.Internal compute tiers (T1 to TN): Cloud Run microservices (
INGRESS_TRAFFIC_INTERNAL_ONLY), Direct VPC Egress configured withegress = "ALL_TRAFFIC", Private Google Access enabled on the subnet, and a Cloud DNS Managed Private Zone (google_dns_managed_zone) forrun.app.bound tovpc_networkmapping*.run.appdirectly to Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30) when calling internal*.run.appURLs, 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_ruleexplicitly permitting outbound TCP port 5432 to Cloud SQL PSC IP and TCP port 443 to Private Google Access VIPs199.36.153.4/30, 199.36.153.8/30onallow_backend_db_egress), and optional VPC Service Controls.
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.Draft solution architecture and generate Terraform &
gcloudCLI 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.mdextension (e.g., workload_name_architecture_report-20260701T212820Z.md). Verify that all 9 security boundaries fromassets/main.tfare 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).Request review and iterate: Present the solution architecture (and Terraform code,
gcloudscript, 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
Retrieve relevant building block templates from the
assets/directory. Important: Use the code inassets/main.tfas the foundation for your Terraform implementation plan (assets/output-template.mdfor architecture structure).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.).
Generate Infrastructure as Code (IaC) (
Architectural Specifications): Retrieve relevant architectural and hierarchy guidance fromreferences/non-negotiable-architectural-rules.md. Base code strictly on the building blocks inassets/main.tf(Section 1.5for Cloud NGFW firewall policies,Section 5.1for Tier 1,Section 5.2for Tiers 2..N), ensuringdatabase_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, andgoogle_compute_network_firewall_policy_rulewithenable_logging = var.enable_monitoring). NEVER generate legacygoogle_compute_firewallresources or revert to older database versions likePOSTGRES_15.Write deployment instructions & README.md: Draft comprehensive step-by-step deployment instructions (or a complete
README.mdartifact), ensuring you include:Instructions to initialize and apply Terraform (
terraform init,terraform apply). Zero-Install Environment Recommendation: Explicitly recommend runningterraformcommands and your generated automated validation script inside Google Cloud Shell (https://shell.cloud.google.com), wherepython3,gcloud, andterraformare 100% pre-installed and authenticated out of the box so developers without local SDKs can deploy and validate immediately.Step-by-Step
gcloudCLI Deployment Commands (Bottom-Up Wiring): In Section 6.3 ("Step-by-step gcloud CLI deployment commands") insideassets/output-template.md, provide a complete, self-contained sequence ofgcloudCLI 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_18when 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-varsinto upstream services.Explanation of all Terraform variables, explicitly including and documenting the
enable_vpc_scanduse_self_signed_certvariables (explaining how settinguse_self_signed_cert = trueenables immediate sandbox verification viacurl -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) whenenable_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 forrun.app.bound tovpc_network, mapping*.run.appdirectly to Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30), alongside external DNS records and database schema initialization.
Request review: Present the implementation plan to the user for approval. Iterate as needed.
Phase 4: Solution validation
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) becomesACTIVE(checking--globalstatus or regional equivalents).Frontend Ingress Block: Verify that direct internet access targeting the Tier 1 Frontend's default
*.run.appURL is blocked (HTTP 403 Forbiddenfrom edge screening).Backend Ingress Block: Verify that direct internet access targeting internal compute tiers'
*.run.appURLs (INGRESS_TRAFFIC_INTERNAL_ONLY) is blocked across all internal microservice tiers (HTTP 404 Not FoundorHTTP 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 200to399).Edge WAF Protection: Verify that a simulated SQL injection request (
/?id=1%20OR%201=1on the custom domain) is intercepted and blocked (HTTP 403 Forbiddenfrom 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).
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/subprocesslibraries, or a cross-platform bash/PowerShell script) customized precisely to the user's deployed domain, SSL certificate name, and exact multi-tier*.run.appURIs.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)).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.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
- ATTRIBUTION.mdAdded by AutoGineer912 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md21.6 KiB
- assets/main.tf30.2 KiB
- assets/output-template.md15.8 KiB
- references/attribution.md1.9 KiB
- references/non-negotiable-architectural-rules.md8.3 KiB
- references/related-guidance.md27.9 KiB
assets/output-template.md
<!-- Use this template to compile the solution architecture and code generated based on the instructions in SKILL.md. -->
<!-- disableFinding(all) -->
<!-- mdlint off -->
Google Cloud solution architecture: [Workload Name]
Note: Standalone text or instructions enclosed between [ and ] (e.g., [Workload Name] or [Paste code here]) represent placeholder instructions or sample text that are replaced by the agent when populating this template.
1. Executive summary and workload overview
[A brief description of the workload, its business goals, and the high-level N-Tier (multi-tier) serverless solution architecture proposed across your compute and data tiers.]
2. Requirements and current state
2.1. Functional requirements
Business processes: [Details of the business processes supported]
Activities and use cases: [Details of the key activities and use cases]
2.2. Non-functional requirements
Security & Zero-Trust: [Details of security requirements including single-domain reverse proxy, WAF mitigation, VPC-internal ingress isolation (
INGRESS_TRAFFIC_INTERNAL_ONLY), and optional VPC Service Controls]Reliability & Availability: [Details of reliability constraints, SLA targets, auto-scaling concurrency, and multi-zone regional high availability]
Cost: [Details of cost constraints, serverless $0 idle cost preferences (
ALL_TRAFFIC+ PGA), and pricing models]Operations & Observability: [Details of monitoring, structured logging, database Query Insights, and continuous deployment requirements]
Performance: [Details of latency, connection pooling, Cloud CDN caching, and Memorystore Redis caching requirements]
Sustainability: [Details of serverless resource optimization and carbon footprint reduction strategies]
2.3. Current state
[If applicable, describe the current on-premises, legacy v1 Cloud Run, or other-cloud architecture.]
Current infrastructure: [Details of existing setup]
Pain points and drivers for migration/redesign: [Details of drivers for migration/redesign]
2.4. Dependencies
Internal dependencies: [Details of internal dependencies including existing VPCs, domain names, and downstream APIs]
External dependencies: [Details of third-party SaaS products and on-premises tools]
3. Technical decomposition of the workload
[Decompose the workload into distinct logical tiers across the request lifecycle, ensuring strict security boundary segregation:]
Tier 1 presentation tier (frontend / reverse proxy): Public-facing UI rendering and gateway proxy service (
google_cloud_run_v2_service.frontend). Ingress restricted strictly to Application Load Balancer (INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER).Tier 2..N application tier (internal microservices / business logic): 1 to N internal business logic services (
google_cloud_run_v2_service.backend_application,orders_service, etc.). Ingress restricted strictly to VPC-internal (INGRESS_TRAFFIC_INTERNAL_ONLY).Data tier (persistent database and in-memory cache): Private relational database (
Cloud SQL PostgreSQL 18 Enterprise Editionwithdatabase_version = "POSTGRES_18", Regional HAavailability_type = "REGIONAL", andPrivate Service Connectconfigurationpsc_enabled = true, ipv4_enabled = false) and cache (Memorystore RedisviaPrivate Services Access).Shared security and lifecycle tiers: Container image management (
Artifact Registry), secret credentials (Secret Manager), private internal DNS resolution (Cloud DNS Managed Private Zoneforrun.app.), and zero-trust Cloud NGFW network firewall policies (google_compute_network_firewall_policy,google_compute_network_firewall_policy_association, andgoogle_compute_network_firewall_policy_rule).
4. Proposed solution architecture
4.1. Google Cloud products and features mapping
[Map your confirmed decomposition directly to Google Cloud products based on the
mandatory product mapping specifications in SKILL.md. Justify every selection and note
trade-offs:]
[Populate the following table with the appropriate content at runtime.]
| Component | Recommended Google Cloud product/feature | Justification and citations | Alternatives considered | Pros and cons of alternatives |
|---|
4.2. Architecture diagram
[Mermaid architecture flowchart illustrating the request and data flow across public and private tiers:] [The following diagram is a sample and must be updated to reflect actual recommendation if necessary.]
flowchart TD
User["User (Browser)"] --> LB["Application Load Balancer (Cloud Armor WAF)"]
LB --> Frontend["Presentation tier (Cloud Run - Load Balancer Ingress)"]
Frontend --> Backend["Application tier (Cloud Run - VPC-Internal Ingress)"]
Backend --> Data["Data tier (Cloud SQL & Memorystore Redis via PSC/PSA)"]4.3. Architecture description
Data flow: [Describe the secure request and data payload lifecycle from edge entry point
https://domain.comthrough tier 1 reverse proxying, internal microservice processing, and persistent database/cache storage.]Tasks/control flow: [Describe container startup authentication, least-privilege IAM service account execution (
roles/run.invoker,roles/cloudsql.client), and Cloud SQL sidecar socket connections.]
5. Design and configuration recommendations
[Populate the following subsections with clear, parameter-dense recommendations adhering to Google Cloud Architecture Framework pillars. The included text is a sample and must be updated to reflect actual recommendation if necessary.]
5.1. Security, privacy, and compliance
Edge WAF & Ingress Filtering: Attach Cloud Armor security policy (
google_compute_security_policywithsqli-v33-stablepreconfigured rule) to Application Load Balancer backend service. Tier 1 Frontend ingress is restricted toINGRESS_TRAFFIC_INTERNAL_LOAD_BALANCERto prevent direct*.run.appURL bypass.VPC-Internal Compute Ingress & Cloud DNS: Intermediate/backend microservices (T2..TN) are restricted strictly to
INGRESS_TRAFFIC_INTERNAL_ONLY. Deploy a Cloud DNS Managed Private Zone (google_dns_managed_zone) forrun.app.bound tovpc_networkwithgoogle_dns_record_setmapping*.run.appto Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30) soegress = "ALL_TRAFFIC"requests resolve internally without hitting default-deny firewalls or public IP routing.Cloud NGFW Egress Firewalls & Sidecar Cert Exchange (
443): Enforce zero-trust Cloud NGFW network firewall policies (google_compute_network_firewall_policy_rule) with default-deny outbound (0.0.0.0/0, priority 65534). Allow frontend egress to backend / PGA VIPs (80, 443), and backend egress (allow_backend_db_egress) to Cloud SQL PSC IP (TCP 5432) and PGA VIPs (TCP 443 on199.36.153.4/30, 199.36.153.8/30) so the Cloud SQL Auth Proxy sidecar can querysqladmin.googleapis.comon startup for IAM certificate exchange.Cloud SQL Auth Proxy & IAM Database Auth (
DB_SOCKET_PATH): Mount Cloud SQL Auth Proxy sidecar viacloud_sql_instancevolume (/cloudsql/project:region:instanceUnix socket). Configure IAM DB authentication (cloudsql.iam_authentication = on,roles/cloudsql.clientviagoogle_sql_user). RecommendDB_SOCKET_PATH(/cloudsql/...Unix socket) as the primary/default path over direct TCP (DB_PSC_ENDPOINT).VPC Service Controls Perimeter: Document/support wrapping
run.googleapis.com,sqladmin.googleapis.com, andsecretmanager.googleapis.comin an Org-level VPC-SC perimeter whenenable_vpc_sc = true.Regional Sovereignty (if applicable): For EU/regional data residency compliance, deploy Regional External ALB (
google_compute_region_backend_service), omit Cloud CDN, provision a regional proxy-only subnet (purpose = "REGIONAL_MANAGED_PROXY"), and specifynetworkon the regional forwarding rule (google_compute_forwarding_rule).
5.2. Reliability
Cloud SQL PostgreSQL Regional HA & PSC: Provision Cloud SQL for PostgreSQL (
POSTGRES_18) Enterprise Edition with Regional High Availability (availability_type = "REGIONAL", point-in-time recovery enabled), and connect via Private Service Connect (psc_enabled = true, ipv4_enabled = false,google_compute_forwarding_rule).Redundant Serverless Deployment: Cloud Run v2 automatically distributes instances across physical zones in
var.region. Configurescaling.min_instance_countandmax_instance_countto eliminate cold-start latency and protect downstream tiers.
5.3. Operational excellence
Structured Logging & Error Reporting: Emit structured JSON logs (
severity,message,trace) for automated ingestion in Logs Explorer and unhandled exception grouping in Cloud Error Reporting.VPC Flow Logs & Firewall Policy Logging: Enable VPC Flow Logs (
flow_sampling = 0.1,aggregation_interval = "INTERVAL_1_MIN") on Cloud Run subnet and firewall logging (enable_logging = var.enable_monitoring) for network access auditing.Database Insights & Synthetic Probes: Enable Cloud SQL Query Insights (
query_insights_enabled = true) for query execution and contention auditing. Configure Cloud Monitoring Uptime Checks (/healthz) and threshold alerts for Frontend HTTP 5xx error rates.Infrastructure as Code (IaC): Manage all infrastructure using modular Terraform (
assets/main.tf) with stateful deletion protection (deletion_protection = true).
5.4. Cost optimization
Serverless Idle Efficiency ($0 Baseline): Internal routing via Direct VPC Egress (
ALL_TRAFFIC) + Private Google Access + Cloud DNS private zone operates at $0 idle cost without intermediate internal load balancers.Edge Caching: Enable Cloud CDN (
enable_cdn = true) on Global ALB to cache static assets and reduce Cloud Run container activations and egress fees.
5.5. Performance efficiency
In-Memory Caching: Deploy Memorystore for Redis via Private Services Access (
connect_mode = "PRIVATE_SERVICE_ACCESS") to cache session state and frequent database read queries.Connection Pooling: Implement database connection pooling inside application containers to prevent PostgreSQL connection saturation during traffic spikes.
5.6. Sustainability
Scale-to-Zero Compute: Fully serverless Cloud Run architecture scales compute instances to zero during idle periods, optimizing datacenter utilization and carbon efficiency.
6. Deployment guidance
[The following steps are samples only. Provide complete, actionable deployment instructions, your generated modular Terraform code, and your generated cross-platform verification scripts below.]
6.1. Step-by-step deployment instructions
Zero-Install Environment Recommendation: For immediate deployment without local SDK installations, run all steps below inside Google Cloud Shell (
https://shell.cloud.google.com), whereterraform,python3,gcloud, andgitare 100% pre-installed and authenticated out of the box.
Select Google Cloud Project and Enable APIs:
gcloud config set project [YOUR_PROJECT_ID] gcloud services enable run.googleapis.com sqladmin.googleapis.com redis.googleapis.com \ servicenetworking.googleapis.com secretmanager.googleapis.com monitoring.googleapis.com \ dns.googleapis.comInitialize and Apply Modular Terraform Configuration:
terraform init # For production with a custom domain: terraform apply -var="domain_name=app.mycompany.com" # For sandbox/dev testing over IP with a self-signed certificate: terraform apply -var="use_self_signed_cert=true"DNS Cutover & SSL Validation: If using a Google-managed certificate (
use_self_signed_cert = false), create a DNSArecord at your registrar pointingvar.domain_nameto the outputtedload_balancer_ip. If using self-signed mode (use_self_signed_cert = true), you can test immediately over HTTPS viacurl -k https://[LOAD_BALANCER_IP]/.Optional VPC Service Controls (
enable_vpc_sc) Configuration: If deploying withenable_vpc_sc = true, ensure your active identity is an Organization Access Context Manager Admin and update your service perimeter to include the newly deployed project and required APIs before starting containers.
6.2. Modular infrastructure as code (main.tf)
[Embed your complete, deploy-ready Terraform (main.tf) code generated from
assets/main.tf below, containing Section 5.1 ("Tier 1 presentation tier: frontend reverse proxy") and
replicated Section 5.2 ("Tier 2 application tier: private backend API") building blocks inside assets/main.tf
tailored to the user's workload, ensuring database_version = "POSTGRES_18" is strictly preserved:]
# [Paste complete deploy-ready generated main.tf HCL code here]6.3. Step-by-step gcloud CLI deployment commands
[Replace the following sample code with the complete sequence of gcloud CLI commands required to deploy this exact three-tier architecture manually from the terminal. Ensure the sequence executes in strict bottom-up deployment order (internal data tier -> internal microservices -> public presentation gateway -> external Application Load Balancer), enforces --database-version=POSTGRES_18 for Cloud SQL, and captures dynamic downstream URLs into shell variables to automatically pass them inside --update-env-vars:]
# 1. Create VPC network and private subnet with Private Google Access enabled
[gcloud command to create a VPC network]
[gcloud command to create a subnet]
# 2. Provision data tier (Private Cloud SQL instance with Public IP disabled & Private Redis)
[gcloud command to create a Cloud SQL instance with --database-version=POSTGRES_18 --no-assign-ip --enable-private-service-connect ...]
[gcloud command to create a Redis instance]
# 3. Deploy internal application tier service (strictly VPC-internal ingress & Direct VPC Egress)
[gcloud command to create an application tier service]
# 4. Extract generated internal application tier URL into shell variable for service wiring
[shell command to extract an application tier URL]
# 5. Deploy presentation tier frontend service with load balancer-only ingress, injecting BACKEND_URL right into environment variables
[gcloud command to deploy the presentation tier service]
# 6. Create Serverless NEG and attach to external Application Load Balancer with Cloud Armor WAF
[gcloud command to create a serverless NEG]
# [Paste remaining gcloud compute backend-services / url-maps / target-https-proxies commands here]6.4. Solution verification guide and custom automated validation script
[Embed your custom automated validation script (e.g., self-contained
cross-platform Python script using standard urllib / subprocess or
cross-platform shell script) generated per Phase 4 validation steps across SSL
provisioning, Tier 1 ingress blocking, Tier 2..N internal VPC ingress blocking,
Application Load Balancer reachability, and Cloud Armor WAF SQLi interception:]
# [Paste custom generated verification script code here]Execution Commands:
python3 validate.py <custom_domain> <ssl_cert_name> <frontend_run_url> [internal_run_url_1 ...]7. References
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
- 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.
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