ComputeCompute
Part of the Cloud knowledge base — GCP deep dive. Complements DevOps Roadmap.
Tổng quan
Google Cloud cung cấp một dải các lựa chọn compute, từ máy ảo thuần túy cho tới các container serverless được quản lý hoàn toàn. Lựa chọn đúng phụ thuộc vào việc bạn muốn tự sở hữu bao nhiêu phần trong operational stack thay vì giao cho Google, workload của bạn scale ra sao, và nó được đóng gói thế nào (VM image, container, hay mã nguồn thuần).
Các dịch vụ cốt lõi, từ nhiều quyền kiểm soát nhất tới ít gánh nặng vận hành nhất:
| Dịch vụ | Mức trừu tượng | Bạn quản lý | Google quản lý | Tương đương AWS |
|---|---|---|---|---|
| Compute Engine (GCE) | Máy ảo | OS, patching, cấu hình scaling | Phần cứng, hypervisor, network | EC2 |
| Google Kubernetes Engine (GKE) | Managed Kubernetes | Workload, (một phần) node | Control plane, (Autopilot) node | EKS |
| Cloud Run | Container serverless | Container image | Mọi thứ còn lại, autoscaling | App Runner / Fargate |
| Cloud Functions | Function serverless | Mã function | Runtime, scaling, hạ tầng | Lambda |
| App Engine | Managed PaaS | Mã ứng dụng | Runtime + hạ tầng | Elastic Beanstalk |
Một mô hình tư duy hữu ích: khi bạn đi xuống trong bảng, bạn đánh đổi quyền kiểm soát và tính linh hoạt để giảm gánh nặng vận hành, và thường là để có mô hình tính phí chi tiết hơn (scale-to-zero).
Kiến thức nền tảng
Compute Engine (GCE)
Compute Engine cung cấp các máy ảo có thể cấu hình chạy trên hạ tầng của Google. Một VM instance được định nghĩa bởi machine type (vCPU + bộ nhớ), một boot disk (từ một image), một zone, và cấu hình network.
Machine families nhóm các machine type theo profile workload:
| Family | Series (ví dụ) | Tối ưu cho |
|---|---|---|
| General purpose | E2, N2, N2D, N4, C3, C4 | Cân bằng giá/hiệu năng, web server, DB nhỏ/vừa |
| Compute optimized | C2, C2D, H3 | Hiệu năng cao mỗi core, gaming, HPC, ad serving |
| Memory optimized | M1, M2, M3, M4 | DB lớn in-memory (SAP HANA), analytics |
| Accelerator optimized | A2, A3, G2 | Workload GPU/TPU, training/inference ML |
| Storage optimized | Z3 | Mật độ local SSD cao, DB scale-out |
Trong một family bạn chọn một machine type như e2-standard-4 (4 vCPU, 16 GB) hoặc một custom machine type khi các shape định sẵn gây lãng phí tài nguyên. E2 là series general-purpose rẻ nhất; C3/C4/N4 chạy trên phần cứng mới hơn với hiệu năng tốt hơn.
Images định nghĩa nội dung boot disk. Google cung cấp public images (Debian, Ubuntu, RHEL, Windows Server, Container-Optimized OS). Bạn có thể build custom images (đã tích hợp sẵn phần mềm của bạn) hoặc dùng một base image kèm startup script.
Startup scripts chạy khi khởi động để cấu hình instance:
gcloud compute instances create web-1 \
--zone=us-central1-a \
--machine-type=e2-medium \
--image-family=debian-12 --image-project=debian-cloud \
--metadata=startup-script='#! /bin/bash
apt-get update
apt-get install -y nginx
echo "Hello from $(hostname)" > /var/www/html/index.html'
Spot VMs (kế thừa của preemptible VMs) cho mức giảm giá 60-91% đổi lại không có cam kết về tính khả dụng — Google có thể thu hồi chúng với thông báo trước 30 giây. Lý tưởng cho các workload chịu lỗi tốt (fault-tolerant), batch, hoặc stateless. Preemptible VMs là biến thể cũ hơn giới hạn vòng đời 24 giờ; Spot VMs không có thời gian chạy tối đa.
Managed Instance Groups (MIGs) & autoscaling
Một Managed Instance Group chạy các VM giống hệt nhau từ một instance template, cung cấp:
- Autoscaling dựa trên CPU utilization, load-balancing capacity, metric của Cloud Monitoring, hoặc lịch (schedule).
- Autohealing qua health check — các VM không khỏe mạnh sẽ được tạo lại.
- Rolling updates / canary trên toàn nhóm.
- Phân phối regional (nhiều zone) cho tính sẵn sàng cao.
# 1. Tạo một instance template
gcloud compute instance-templates create web-tmpl \
--machine-type=e2-medium \
--image-family=debian-12 --image-project=debian-cloud \
--metadata=startup-script='#! /bin/bash
apt-get update && apt-get install -y nginx'
# 2. Tạo một regional MIG từ template
gcloud compute instance-groups managed create web-mig \
--template=web-tmpl \
--size=3 \
--region=us-central1
# 3. Cấu hình autoscaling (mục tiêu 60% CPU, 2-10 instance)
gcloud compute instance-groups managed set-autoscaling web-mig \
--region=us-central1 \
--min-num-replicas=2 --max-num-replicas=10 \
--target-cpu-utilization=0.6 --cool-down-period=90
MIG nằm sau Cloud Load Balancing để phân phối lưu lượng và là pattern kinh điển cho các tầng web dựa trên VM có khả năng scale.
Tương đương trong Terraform:
resource "google_compute_instance_template" "web" {
name_prefix = "web-tmpl-"
machine_type = "e2-medium"
disk {
source_image = "debian-cloud/debian-12"
auto_delete = true
boot = true
}
network_interface { network = "default" }
metadata = {
startup-script = "apt-get update && apt-get install -y nginx"
}
lifecycle { create_before_destroy = true }
}
resource "google_compute_region_instance_group_manager" "web" {
name = "web-mig"
region = "us-central1"
base_instance_name = "web"
version { instance_template = google_compute_instance_template.web.id }
target_size = 3
}
Google Kubernetes Engine (GKE)
GKE là Kubernetes được quản lý của Google. Google vận hành control plane (API server, etcd, scheduler); bạn triển khai các workload Kubernetes tiêu chuẩn.
Standard vs Autopilot:
| Khía cạnh | GKE Standard | GKE Autopilot |
|---|---|---|
| Quản lý node | Bạn cấu hình/quản lý node pool | Google provision/quản lý node |
| Tính phí | Theo node (VM) | Theo resource request của pod |
| Bin-packing | Trách nhiệm của bạn | Google tối ưu |
| Tính linh hoạt | Đầy đủ (DaemonSet, cấu hình node tùy chỉnh, GPU) | Hạn chế, mặc định được hardening |
| Phù hợp cho | Kiểm soát chi tiết, phần cứng đặc biệt | Không phải bận tâm, secure-by-default |
Node pools là các nhóm node có cùng cấu hình (machine type, disk, label). Một cluster có thể có nhiều pool — ví dụ một pool chung cộng một pool GPU hoặc một pool Spot cho batch job.
Workload Identity là cách được khuyến nghị để pod xác thực với các API của Google Cloud. Nó ánh xạ một Kubernetes service account tới một IAM service account, loại bỏ nhu cầu mount các service account key tồn tại lâu dài:
# Gắn KSA với GSA
gcloud iam service-accounts add-iam-policy-binding \
my-gsa@PROJECT.iam.gserviceaccount.com \
--role=roles/iam.workloadIdentityUser \
--member="serviceAccount:PROJECT.svc.id.goog[NAMESPACE/my-ksa]"
Cloud Run
Cloud Run chạy các container stateless tự động scale, bao gồm cả scale to zero (không tốn chi phí khi rảnh). Bạn cung cấp một container lắng nghe trên $PORT; Google lo việc provisioning, TLS, và autoscaling.
Services vs Jobs:
- Services xử lý request (HTTP, gRPC, event) và luôn sẵn sàng phục vụ. Chúng scale theo lượng request.
- Jobs chạy tới khi hoàn thành (batch/ETL/migration) rồi thoát. Chúng có thể chạy các task song song và được kích hoạt thủ công, theo lịch, hoặc qua Cloud Scheduler/Workflows.
Concurrency — một container instance Cloud Run có thể xử lý nhiều request đồng thời (mặc định tới 80, tối đa 1000). Concurrency cao hơn cải thiện mức tận dụng và giảm chi phí nhưng yêu cầu ứng dụng thread-safe. Đặt concurrency bằng 1 cho workload CPU-bound hoặc không thread-safe.
gcloud run deploy my-api \
--image=us-docker.pkg.dev/PROJECT/repo/my-api:v1 \
--region=us-central1 \
--concurrency=80 \
--cpu=1 --memory=512Mi \
--min-instances=0 --max-instances=20 \
--allow-unauthenticated
Scale-to-zero nghĩa là bạn chỉ trả tiền khi request đang được xử lý (cộng tùy chọn min-instances để giữ warm capacity). Cold start là cái giá phải trả; đặt --min-instances=1 cho các service nhạy cảm với độ trễ.
Một Cloud Run job (chạy tới khi hoàn thành rồi thoát):
gcloud run jobs create migrate-db \
--image=us-docker.pkg.dev/PROJECT/repo/migrator:v1 \
--region=us-central1 \
--tasks=1 --max-retries=3 --task-timeout=600
gcloud run jobs execute migrate-db --region=us-central1 --wait
Cloud Functions (gen 2)
Cloud Functions (thế hệ 2) được xây trên Cloud Run và Eventarc, nên kế thừa concurrency, timeout dài hơn (tới 60 phút), và instance lớn hơn của Cloud Run. Nó chạy các function đơn mục đích được kích hoạt bởi HTTP hoặc event (Pub/Sub, Cloud Storage, Firestore, Eventarc).
gcloud functions deploy process-upload \
--gen2 --runtime=nodejs20 \
--region=us-central1 \
--trigger-bucket=my-uploads \
--entry-point=processUpload \
--memory=256Mi
Dùng Functions cho mã kết dính (glue code) hướng sự kiện; dùng Cloud Run khi bạn cần toàn quyền kiểm soát container hoặc một service chạy dài.
App Engine (tóm tắt)
App Engine là PaaS nguyên bản của Google. Hai môi trường:
- Standard — chạy sandbox, scale nhanh (kể cả về zero), các runtime ngôn ngữ cụ thể, phù hợp nhất cho các ứng dụng web/API stateless.
- Flexible — chạy ứng dụng của bạn trong container Docker trên các VM GCE được quản lý, linh hoạt hơn (bất kỳ runtime, tiến trình nền) nhưng scale chậm hơn và không scale-to-zero.
Với hầu hết workload mới, Cloud Run về cơ bản đã thay thế App Engine Flexible, và Cloud Run/Functions bao phủ các use case của Standard với tính linh hoạt cao hơn.
Khái niệm chính
Chọn một dịch vụ compute
- ?Có phải là một function đơn hướng sự kiện (glue code)?CóCloud Functionsgen 2
- ?Có phải là một container/web service/API stateless?CóCloud Runscale-to-zero, tính phí theo request, ít vận hành
- ?Bạn có cần Kubernetes (microservice phức tạp, service mesh, custom operator, tính di động, GPU ở quy mô lớn)?CóGKEAutopilot để không phải bận tâm, Standard để kiểm soát đầy đủ
- ?Bạn có cần toàn quyền kiểm soát OS, phần mềm có license, GPU trên VM, lift-and-shift, hoặc machine shape chuyên biệt?CóCompute Enginekèm MIG để scale
Quy tắc kinh nghiệm:
- Mặc định chọn Cloud Run cho các service stateless mới — ít vận hành nhất, kinh tế tốt.
- Chọn GKE khi bạn đã chạy Kubernetes, cần multi-container pod, service mesh, hoặc scheduling phức tạp.
- Chọn Compute Engine cho legacy/lift-and-shift, workload stateful, licensing, hoặc khi cần một OS/kernel cụ thể.
- Dùng Cloud Functions cho các event handler nhỏ và tích hợp.
Region và zone
Tài nguyên có phạm vi: zonal (một VM đơn, disk zonal), regional (MIG regional, disk regional), hoặc global (image, global load balancer). Trải rộng qua các zone/region là nền tảng của tính sẵn sàng cao.
Sustained use & committed use discounts
- Sustained use discounts (SUDs) áp dụng tự động cho các VM chạy phần lớn thời gian trong tháng.
- Committed use discounts (CUDs) giảm tới ~57% cho cam kết 1 hoặc 3 năm với một lượng tài nguyên — rất tốt cho tải nền ổn định.
Cold start
Cả Cloud Run và Cloud Functions đều “scale to zero”, nên request đầu tiên sau một khoảng rảnh sẽ chịu một cold start (khởi động container + init ứng dụng). Giảm thiểu bằng min-instances, image nhỏ hơn, lazy loading các dependency nặng, và CPU boost khi khởi động.
Best Practices
-
Mặc định ưu tiên managed/serverless trước. Bắt đầu với Cloud Run hoặc Functions và chỉ chuyển sang GKE/GCE khi gặp giới hạn thực sự. Lý do: ít việc vận hành không tạo giá trị khác biệt, tự động scale, và kinh tế trả-theo-sử-dụng.
-
Dùng instance template + MIG, không bao giờ tạo pet VM thủ công. Lý do: template khiến instance có thể tái tạo và cho phép autohealing, autoscaling, rolling update — coi VM như “cattle”, không phải “pet”.
-
Right-size machine type và dùng custom type khi cần. Khớp vCPU/bộ nhớ với mức dùng thực tế; dùng gợi ý từ Recommender. Lý do: các shape định sẵn thường over-provision một chiều, gây lãng phí tiền.
-
Dùng Spot VM cho workload chịu lỗi tốt và batch. Lý do: tiết kiệm 60-91%; kết hợp với MIG và autohealing, các gián đoạn được hấp thụ một cách mượt mà.
-
Mua Committed Use Discount cho tải nền ổn định. Lý do: tiết kiệm tới ~57% cho workload có thể dự đoán; giữ on-demand/Spot cho các đỉnh biến động.
-
Ưu tiên GKE Autopilot trừ khi bạn cần quyền kiểm soát của Standard. Lý do: trả theo pod, Google hardening và quản lý node, ít bề mặt vận hành và ít cấu hình sai hơn.
-
Dùng Workload Identity thay vì service account key trong GKE. Lý do: loại bỏ các key tải xuống được tồn tại lâu dài — vector rò rỉ credential phổ biến nhất trên cloud.
-
Điều chỉnh concurrency của Cloud Run một cách có chủ đích. Lý do: concurrency cao hơn giảm chi phí và cold start cho ứng dụng I/O-bound; đặt bằng 1 cho code CPU-bound hoặc không thread-safe để tránh tranh chấp.
-
Đặt
min-instancescho các service Cloud Run nhạy cảm với độ trễ. Lý do: giữ các instance warm để tránh độ trễ cold-start, trong khi vẫn scale xuống một sàn thấp thay vì một cụm cố định lớn. -
Bake golden image cho các stack khởi động chậm; dùng startup script cho cấu hình nhẹ. Lý do: custom image cắt giảm thời gian khởi động và loại bỏ các lỗi khi cài đặt; startup script giữ template linh hoạt cho các chỉnh sửa nhỏ.
-
Gắn health check cho mọi MIG và load balancer. Lý do: cho phép autohealing và ngăn lưu lượng đi tới các instance hỏng.
-
Phân phối qua nhiều zone (regional MIG / GKE nhiều zone). Lý do: sống sót qua sự cố một zone; tài nguyên regional là chuẩn cơ bản cho HA production.
-
Giữ container tối giản và stateless. Lý do: cold start nhanh hơn, bề mặt tấn công nhỏ hơn, và scale ngang sạch sẽ; đẩy state sang các database/object storage được quản lý.
-
Dùng service account theo nguyên tắc đặc quyền tối thiểu cho mỗi workload. Lý do: một VM/pod/function bị xâm phạm chỉ bị giới hạn trong các quyền hẹp của riêng nó thay vì một account mặc định rộng.
-
Bật Shielded VM và OS Login cho Compute Engine. Lý do: Shielded VM bảo vệ chống rootkit ở mức boot; OS Login tập trung hóa quyền truy cập SSH qua IAM thay vì quản lý key trên từng instance.
-
Tự động hóa hạ tầng với Terraform / Config Connector. Lý do: hạ tầng có thể tái tạo, review được, và version-controlled tốt hơn click-ops và drift.
Tài liệu tham khảo
- Compute Engine documentation
- Machine families resource and comparison guide
- Spot VMs
- Managed Instance Groups
- Autoscaling groups of instances
- GKE documentation
- GKE Autopilot overview
- GKE Workload Identity
- Cloud Run documentation
- Cloud Run jobs
- Cloud Functions (2nd gen)
- App Engine documentation
- Choosing a compute option (hosting decision tree)
- Committed use discounts
Part of the Cloud knowledge base — GCP deep dive. Complements DevOps Roadmap.
Overview
Google Cloud offers a spectrum of compute options, from raw virtual machines to fully managed, serverless containers. The right choice depends on how much of the operational stack you want to own versus delegate to Google, how your workload scales, and how it is packaged (VM image, container, or plain source code).
The core services, from most control to least operational overhead:
| Service | Abstraction | You manage | Google manages | AWS equivalent |
|---|---|---|---|---|
| Compute Engine (GCE) | Virtual machines | OS, patching, scaling config | Hardware, hypervisor, network | EC2 |
| Google Kubernetes Engine (GKE) | Managed Kubernetes | Workloads, (some) nodes | Control plane, (Autopilot) nodes | EKS |
| Cloud Run | Serverless containers | Container image | Everything else, autoscaling | App Runner / Fargate |
| Cloud Functions | Serverless functions | Function code | Runtime, scaling, infra | Lambda |
| App Engine | Managed PaaS | App code | Runtime + infra | Elastic Beanstalk |
A useful mental model: as you move down the table you trade control and flexibility for reduced operational burden and, often, finer-grained (scale-to-zero) billing.
Fundamentals
Compute Engine (GCE)
Compute Engine provides configurable virtual machines running on Google’s infrastructure. A VM instance is defined by a machine type (vCPU + memory), a boot disk (from an image), a zone, and a network configuration.
Machine families group machine types by workload profile:
| Family | Series (examples) | Optimized for |
|---|---|---|
| General purpose | E2, N2, N2D, N4, C3, C4 | Balanced price/performance, web servers, small/medium DBs |
| Compute optimized | C2, C2D, H3 | High per-core performance, gaming, HPC, ad serving |
| Memory optimized | M1, M2, M3, M4 | Large in-memory DBs (SAP HANA), analytics |
| Accelerator optimized | A2, A3, G2 | GPU/TPU workloads, ML training/inference |
| Storage optimized | Z3 | High local SSD density, scale-out DBs |
Within a family you pick a machine type such as e2-standard-4 (4 vCPU, 16 GB) or a custom machine type when predefined shapes waste resources. E2 is the cheapest general-purpose series; C3/C4/N4 run on newer hardware with better performance.
Images define the boot disk contents. Google provides public images (Debian, Ubuntu, RHEL, Windows Server, Container-Optimized OS). You can build custom images (baked with your software) or use a base image plus a startup script.
Startup scripts run on boot to configure the instance:
gcloud compute instances create web-1 \
--zone=us-central1-a \
--machine-type=e2-medium \
--image-family=debian-12 --image-project=debian-cloud \
--metadata=startup-script='#! /bin/bash
apt-get update
apt-get install -y nginx
echo "Hello from $(hostname)" > /var/www/html/index.html'
Spot VMs (the successor to preemptible VMs) offer 60-91% discounts in exchange for no availability guarantee — Google can reclaim them with 30 seconds notice. Ideal for fault-tolerant, batch, or stateless workloads. Preemptible VMs are the older variant capped at a 24-hour lifetime; Spot VMs have no max runtime.
Managed Instance Groups (MIGs) & autoscaling
A Managed Instance Group runs identical VMs from an instance template, providing:
- Autoscaling based on CPU utilization, load-balancing capacity, Cloud Monitoring metrics, or schedules.
- Autohealing via health checks — unhealthy VMs are recreated.
- Rolling updates / canary deployments across the group.
- Regional (multi-zone) distribution for high availability.
# 1. Create an instance template
gcloud compute instance-templates create web-tmpl \
--machine-type=e2-medium \
--image-family=debian-12 --image-project=debian-cloud \
--metadata=startup-script='#! /bin/bash
apt-get update && apt-get install -y nginx'
# 2. Create a regional MIG from the template
gcloud compute instance-groups managed create web-mig \
--template=web-tmpl \
--size=3 \
--region=us-central1
# 3. Configure autoscaling (target 60% CPU, 2-10 instances)
gcloud compute instance-groups managed set-autoscaling web-mig \
--region=us-central1 \
--min-num-replicas=2 --max-num-replicas=10 \
--target-cpu-utilization=0.6 --cool-down-period=90
MIGs sit behind Cloud Load Balancing to distribute traffic and are the classic pattern for scalable VM-based web tiers.
The equivalent in Terraform:
resource "google_compute_instance_template" "web" {
name_prefix = "web-tmpl-"
machine_type = "e2-medium"
disk {
source_image = "debian-cloud/debian-12"
auto_delete = true
boot = true
}
network_interface { network = "default" }
metadata = {
startup-script = "apt-get update && apt-get install -y nginx"
}
lifecycle { create_before_destroy = true }
}
resource "google_compute_region_instance_group_manager" "web" {
name = "web-mig"
region = "us-central1"
base_instance_name = "web"
version { instance_template = google_compute_instance_template.web.id }
target_size = 3
}
Google Kubernetes Engine (GKE)
GKE is Google’s managed Kubernetes. Google runs the control plane (API server, etcd, scheduler); you deploy standard Kubernetes workloads.
Standard vs Autopilot:
| Aspect | GKE Standard | GKE Autopilot |
|---|---|---|
| Node management | You configure/manage node pools | Google provisions/manages nodes |
| Billing | Per node (VM) | Per pod resource request |
| Bin-packing | Your responsibility | Google optimizes |
| Flexibility | Full (DaemonSets, custom node config, GPUs) | Constrained, hardened defaults |
| Best for | Fine control, special hardware | Hands-off, secure-by-default |
Node pools are groups of nodes with the same configuration (machine type, disk, labels). A cluster can have multiple pools — e.g., a general pool plus a GPU pool or a Spot pool for batch jobs.
Workload Identity is the recommended way for pods to authenticate to Google Cloud APIs. It maps a Kubernetes service account to an IAM service account, eliminating the need to mount long-lived service account keys:
# Bind KSA to GSA
gcloud iam service-accounts add-iam-policy-binding \
my-gsa@PROJECT.iam.gserviceaccount.com \
--role=roles/iam.workloadIdentityUser \
--member="serviceAccount:PROJECT.svc.id.goog[NAMESPACE/my-ksa]"
Cloud Run
Cloud Run runs stateless containers that scale automatically, including scale to zero (no cost when idle). You provide a container listening on $PORT; Google handles provisioning, TLS, and autoscaling.
Services vs Jobs:
- Services handle requests (HTTP, gRPC, events) and stay ready to serve. They scale on request volume.
- Jobs run to completion (batch/ETL/migrations) and exit. They can run parallel tasks and are triggered manually, on a schedule, or via Cloud Scheduler/Workflows.
Concurrency — a single Cloud Run container instance can handle multiple simultaneous requests (default up to 80, max 1000). Higher concurrency improves utilization and lowers cost but requires a thread-safe app. Set concurrency to 1 for CPU-bound or non-thread-safe workloads.
gcloud run deploy my-api \
--image=us-docker.pkg.dev/PROJECT/repo/my-api:v1 \
--region=us-central1 \
--concurrency=80 \
--cpu=1 --memory=512Mi \
--min-instances=0 --max-instances=20 \
--allow-unauthenticated
Scale-to-zero means you pay only while requests are processed (plus optional min-instances for warm capacity). Cold starts are the trade-off; set --min-instances=1 for latency-sensitive services.
A Cloud Run job (runs to completion, then exits):
gcloud run jobs create migrate-db \
--image=us-docker.pkg.dev/PROJECT/repo/migrator:v1 \
--region=us-central1 \
--tasks=1 --max-retries=3 --task-timeout=600
gcloud run jobs execute migrate-db --region=us-central1 --wait
Cloud Functions (gen 2)
Cloud Functions (2nd gen) is built on Cloud Run and Eventarc, so it inherits Cloud Run’s concurrency, longer timeouts (up to 60 min), and larger instances. It runs single-purpose functions triggered by HTTP or events (Pub/Sub, Cloud Storage, Firestore, Eventarc).
gcloud functions deploy process-upload \
--gen2 --runtime=nodejs20 \
--region=us-central1 \
--trigger-bucket=my-uploads \
--entry-point=processUpload \
--memory=256Mi
Use Functions for event-driven glue code; use Cloud Run when you need full container control or a long-running service.
App Engine (brief)
App Engine is Google’s original PaaS. Two environments:
- Standard — sandboxed, fast scaling (including to zero), specific language runtimes, best for stateless web/API apps.
- Flexible — runs your app in Docker containers on managed GCE VMs, more flexibility (any runtime, background processes) but slower scaling and no scale-to-zero.
For most new workloads Cloud Run has largely superseded App Engine Flexible, and Cloud Run/Functions cover Standard use cases with more flexibility.
Key Concepts
Choosing a compute service
- ?Is it a single event-driven function (glue code)?YesCloud Functionsgen 2
- ?Is it a stateless container/web service/API?YesCloud Runscale-to-zero, per-request billing, minimal ops
- ?Do you need Kubernetes (complex microservices, service mesh, custom operators, portability, GPUs at scale)?YesGKEAutopilot for hands-off, Standard for full control
- ?Do you need full OS control, licensed software, GPUs on VMs, lift-and-shift, or specialized machine shapes?YesCompute Enginewith MIGs for scale
Rules of thumb:
- Default to Cloud Run for new stateless services — least ops, good economics.
- Choose GKE when you already run Kubernetes, need multi-container pods, service mesh, or complex scheduling.
- Choose Compute Engine for legacy/lift-and-shift, stateful workloads, licensing, or when you need a specific OS/kernel.
- Use Cloud Functions for small event handlers and integrations.
Regions and zones
Resources are scoped: zonal (a single VM, zonal disk), regional (regional MIG, regional disk), or global (images, global load balancer). Spreading across zones/regions is the foundation of high availability.
Sustained use & committed use discounts
- Sustained use discounts (SUDs) apply automatically to VMs run for a large fraction of the month.
- Committed use discounts (CUDs) give up to ~57% off for 1- or 3-year commitments to a resource amount — great for steady baseline load.
Cold starts
Both Cloud Run and Cloud Functions “scale to zero”, so the first request after an idle period incurs a cold start (container boot + app init). Mitigate with min-instances, smaller images, lazy loading of heavy dependencies, and CPU boost on startup.
Best Practices
-
Default to managed/serverless first. Start with Cloud Run or Functions and move to GKE/GCE only when you hit a real constraint. Rationale: less undifferentiated ops work, automatic scaling, and pay-for-use economics.
-
Use instance templates + MIGs, never manually created pet VMs. Rationale: templates make instances reproducible and enable autohealing, autoscaling, and rolling updates — treating VMs as cattle, not pets.
-
Right-size machine types and use custom types when needed. Match vCPU/memory to actual usage; use recommendations from the Recommender. Rationale: predefined shapes often over-provision one dimension, wasting money.
-
Use Spot VMs for fault-tolerant and batch workloads. Rationale: 60-91% savings; combined with MIGs and autohealing, interruptions are absorbed gracefully.
-
Buy Committed Use Discounts for steady baseline load. Rationale: up to ~57% savings for predictable workloads; keep on-demand/Spot for variable peaks.
-
Prefer GKE Autopilot unless you need Standard’s control. Rationale: pay per pod, Google hardens and manages nodes, less operational surface and fewer misconfigurations.
-
Use Workload Identity instead of service account keys in GKE. Rationale: eliminates long-lived downloadable keys — the most common cloud credential leak vector.
-
Tune Cloud Run concurrency deliberately. Rationale: higher concurrency lowers cost and cold starts for I/O-bound apps; set to 1 for CPU-bound or non-thread-safe code to avoid contention.
-
Set
min-instancesfor latency-sensitive Cloud Run services. Rationale: keeps warm instances to avoid cold-start latency, while still scaling to a low floor rather than a large fixed fleet. -
Bake golden images for slow-booting stacks; use startup scripts for light config. Rationale: custom images cut boot time and remove install-time failure modes; startup scripts keep templates flexible for small tweaks.
-
Attach health checks to every MIG and load balancer. Rationale: enables autohealing and prevents traffic from reaching broken instances.
-
Distribute across zones (regional MIGs / multi-zone GKE). Rationale: survives single-zone failures; regional resources are the baseline for production HA.
-
Keep containers minimal and stateless. Rationale: faster cold starts, smaller attack surface, and clean horizontal scaling; push state to managed databases/object storage.
-
Use least-privilege service accounts per workload. Rationale: a compromised VM/pod/function is limited to its own narrow permissions rather than a broad default account.
-
Enable Shielded VM and OS Login for Compute Engine. Rationale: Shielded VM protects against boot-level rootkits; OS Login centralizes SSH access via IAM instead of managing keys per instance.
-
Automate infrastructure with Terraform / Config Connector. Rationale: reproducible, reviewable, version-controlled infra beats click-ops and drift.
References
- Compute Engine documentation
- Machine families resource and comparison guide
- Spot VMs
- Managed Instance Groups
- Autoscaling groups of instances
- GKE documentation
- GKE Autopilot overview
- GKE Workload Identity
- Cloud Run documentation
- Cloud Run jobs
- Cloud Functions (2nd gen)
- App Engine documentation
- Choosing a compute option (hosting decision tree)
- Committed use discounts