VM or Cloud Run?
| # | Choose VMs (in a MIG) when… | Choose Cloud Run when… |
|---|---|---|
| 1 | The software needs OS-level setup: special libraries, drivers, a GPU, kernel settings | It runs happily in a container |
| 2 | Load is steady all day, so paying per VM-hour is cheaper than per request | Load is spiky or often near zero; Cloud Run scales to zero |
| 3 | Requests run long, or connections stay open for hours (WebSockets, streaming) | Requests finish within Cloud Run's request timeout |
| 4 | It needs a large local disk or memory cache that should survive between requests | Each request can stand alone |
| 5 | You need control over the machine (OS version, agents, tuning) | You want Google to own patching and scaling |
The shape: template, group, load balancer
| # | Piece | Job | Kadé's value |
|---|---|---|---|
| 1 | Instance template | The recipe for every VM in the group | kade-media-tpl-v1 |
| 2 | Managed instance group | Keeps the right number of VMs from that recipe running | kade-media-mig, regional, asia-southeast1 |
| 3 | Autohealing | Recreates a VM whose app stops answering | HTTP check /healthz, initial delay 180 s |
| 4 | Autoscaler | Changes the number of VMs with load | 2 to 8 VMs, load balancer usage target 80% |
| 5 | Backend service | Connects the group to the load balancer (chapter 12.1, link 4) | kade-media-backend |
Instance templates: the recipe
A template holds everything needed to create one VM. The MIG uses it every time it adds or replaces a VM, so whatever is in the template is what every VM gets:
| # | In the template | Kadé's value | Why it matters |
|---|---|---|---|
| 1 | Machine type | e2-standard-2 | Size per VM; the autoscaler handles the count |
| 2 | Boot image | kade-media-2026-09, a custom image with the app and Ops Agent already installed | New VMs start in seconds. Installing everything at boot makes scale-out slow and fragile |
| 3 | Network interface | kade-vpc, sn-app, no external IP | One wrong template gives every future VM a public address (chapter 3) |
| 4 | Service account | sa-kade-media | Firewall rules target it (chapter 5.1), so new VMs are covered automatically |
| 5 | Metadata | A small startup script that reads config; OS Login inherited from the project | Never set enable-oslogin=FALSE here (chapter 6.2) |
| 6 | Shielded VM, disk size | On; 50 GB balanced disk for the image cache | The cache is rebuilt on a new VM; nothing on the disk must be precious |
The group: zonal or regional
| # | Zonal MIG | Regional MIG | |
|---|---|---|---|
| 1 | Where VMs run | One zone | Spread across zones in the region (up to three) |
| 2 | A zone fails | The whole group is down | The others keep serving; the group rebuilds in the healthy zones |
| 3 | Use for | Batch work, testing | Anything users depend on. Kadé's choice |
kade-media-x7k2, and names change as VMs are replaced. Nothing should point at one VM's name or IP; traffic always goes through the load balancer.A group also has named ports: a label for the port the app listens on, such as http:8080. The backend service refers to the name, not the number, so the port can change in one place.
Two health checks with two different jobs
This is the most confusing part of MIGs, and it causes boot loops. There are two health checks, and they do different things to an unhealthy VM:
| # | Load balancer health check | Autohealing health check | |
|---|---|---|---|
| 1 | Set on | The backend service | The MIG |
| 2 | When a VM fails it | Stop sending it traffic. The VM keeps running | Delete and recreate the VM from the template |
| 3 | Should be | Quick to react: a few seconds | Slower and more patient: only for VMs that will not recover by themselves |
| 4 | Firewall | Both come from 35.191.0.0/16 and 130.211.0.0/22; one rule covers both (chapter 12.1 section 04) |
The setting that prevents disaster is the initial delay: how long autohealing waits after a VM starts before it judges it. See what happens without one:
Shoppers unaffected; the group repairs itself in about 2 minutes
The load balancer's quick check fails after about 10 s, so traffic stops going to the hung VM, and shoppers see nothing wrong. A minute later the slower autohealing check gives up on it too, and the MIG replaces the VM. Two checks, two jobs, both needed.
Show as config
LB check kade-media-hc: every 5 s, 2 failures → out of rotation in ~10 s Autohealing kade-media-heal: every 20 s, 3 failures → recreated after ~60 s
Autoscaling
The autoscaler watches a signal and changes the number of VMs to keep that signal near a target:
| # | Signal | Means | Good for |
|---|---|---|---|
| 1 | Load balancer usage | Requests per VM against the capacity set on the backend service | Web backends behind a load balancer. Kadé's choice |
| 2 | CPU utilization | Average CPU across the group | CPU-bound work; can also be predictive, scaling before a daily peak |
| 3 | A Cloud Monitoring metric | Any metric, such as a queue's length | Workers pulling jobs from a queue |
| 4 | Schedules | A minimum size during set hours | Known peaks: a sale starting at 8 pm |
| # | Setting | Kadé's value | Why |
|---|---|---|---|
| 1 | Minimum VMs | 2 | One VM per zone at least, so a zone failure or a single bad VM never empties the group |
| 2 | Maximum VMs | 8 | A ceiling for cost and for the NAT ports and database connections each VM uses (chapter 7) |
| 3 | Initialization period | 120 s | How long a new VM needs before its numbers count. Too short and the autoscaler adds even more VMs while the first ones are still starting |
| 4 | Scale-in controls | At most 2 VMs removed per 10 minutes | Stops a short dip from removing capacity that the next spike needs |
Each VM handles 80 requests per second; the autoscaler aims for 80% of that. As the evening sale ramps up, VMs are added (about 2 minutes behind demand, while new VMs start), and removed slowly afterwards. Capacity stays above demand all day.
Show as config
--min-num-replicas=2 --max-num-replicas=8 --target-load-balancing-utilization=0.8 (80% of RATE 80 per VM = 64 rps per VM) --cool-down-period=120
Rolling updates, canaries and rollback
A new version means a new template. The MIG moves VMs onto it gradually, controlled by two numbers:
| # | Setting | Means | Kadé's value |
|---|---|---|---|
| 1 | Max surge | How many extra VMs may exist above the target size during the update | 3 (one per zone; a regional MIG needs 0 or at least the number of zones) |
| 2 | Max unavailable | How many VMs may be out of service at once | 0: never go below full capacity |
| 3 | Minimal action | REPLACE (new VM) or RESTART | REPLACE: a new template needs new VMs |
Step through an update. Each square is one VM, labelled with its template:
Serving
- VMv1
- VMv1
- VMv1
- VMv1
- VMv1
- VMv1
6 VMs serving · target 6
6 VMs on v1, target size 6
Connecting the group to the load balancer
The group joins chapter 12.1's chain as the backend of a new backend service, and the URL map sends /media/* to it. Everything else in the chain is shared with kade-api:
Links 1 and 2 are shared with kade-api. The URL map adds one path rule; links 4 and 5 are new.
api.kade.lk/* → kade-api-backend (serverless NEG) · www.kade.lk/media/* → kade-media-backend (MIG)
| # | Backend service setting | Kadé's value | Effect |
|---|---|---|---|
| 1 | Port name | http | Matches the group's named port http:8080 |
| 2 | Balancing mode | RATE, 80 requests per second per VM | "Full" means 80 rps; the autoscaler targets 80% of it |
| 3 | Capacity scaler | 1.0 | Set to 0 to drain a whole group without deleting it, for example before replacing it |
| 4 | Health check | kade-media-hc: HTTP /healthz, 5 s | The quick one from section 05 |
| 5 | Connection draining | 60 s | VMs leaving the group finish their requests (chapter 12.1 section 05) |
| 6 | Cloud Armor, CDN, logging | kade-edge-policy, CDN on (resized images cache well), logging 100% | Exactly as kade-api-backend |
Network rules for VMs in a group
Every network rule from earlier chapters applies to MIG VMs, with one difference: they must hold for VMs that do not exist yet. Put each one where new VMs inherit it:
| # | Need | How, for a MIG | Chapter |
|---|---|---|---|
| 1 | No public address | Template without an external IP; organization policy as a safety net | 3, 17 |
| 2 | Health checks reach the app | Firewall rule from Google's ranges to service account sa-kade-media on 8080 | 5.1 |
| 3 | Outgoing internet (updates, APIs) | Cloud NAT covering sn-app; check ports at maximum size | 7 |
| 4 | Google APIs (Cloud Storage for originals) | Private Google Access on sn-app | 9 |
| 5 | Admin SSH | IAP + OS Login, inherited from project metadata | 6 |
| 6 | Metrics and logs from inside the VM | Ops Agent baked into the image | 16.1 |
Back to Kadé
Commands in this chapter
Commands 1 to 3 are read-only. Commands 4 to 9 change the project.
See the group's VMs and their health
- What it shows: Each VM, its zone, status, current action, template and health.
- What to look for:
RUNNINGandHEALTHY. VMs stuck inRECREATINGagain and again mean a boot loop (section 05).
gcloud compute instance-groups managed list-instances kade-media-mig \ --region=asia-southeast1See the autoscaler's view
- What it shows: Target size, autoscaling policy, and status messages.
- What to look for: Messages such as "maximum number of instances reached", which mean the ceiling is limiting you.
gcloud compute instance-groups managed describe kade-media-mig \ --region=asia-southeast1 --format="yaml(targetSize,autoscaler,status,updatePolicy,versions)"See which VMs autohealing replaced
- What it shows: System events where the MIG recreated a VM after a failed health check.
- What to look for: Frequent entries for new VMs point at the initial delay or a broken image.
gcloud logging read \ 'protoPayload.methodName="compute.instances.repair.recreateInstance"' \ --freshness=1d --limit=20 --format="table(timestamp,protoPayload.resourceName)"Create the template (changes the project)
- What it shows: The recipe, with no external IP (
--no-address) and its own service account. - What to look for: The template in
gcloud compute instance-templates list. It cannot be edited afterwards.
gcloud compute instance-templates create kade-media-tpl-v1 \ --machine-type=e2-standard-2 --image=kade-media-2026-09 --image-project=kade-prod \ --network=kade-vpc --subnet=sn-app --region=asia-southeast1 --no-address \ --service-account=sa-kade-media@kade-prod.iam.gserviceaccount.com --scopes=cloud-platform \ --shielded-secure-boot --boot-disk-size=50GB --boot-disk-type=pd-balancedCreate the regional group with autohealing (changes the project)
- What it shows: Two VMs spread across the region's zones, recreated if
/healthzfails, after a 180 s grace period. - What to look for: Command 1 shows one VM in each of two zones, then
HEALTHY.
gcloud compute health-checks create http kade-media-heal --port=8080 \ --request-path=/healthz --check-interval=20s --unhealthy-threshold=3gcloud compute instance-groups managed create kade-media-mig --region=asia-southeast1 \ --template=kade-media-tpl-v1 --size=2 \ --health-check=kade-media-heal --initial-delay=180gcloud compute instance-groups set-named-ports kade-media-mig \ --region=asia-southeast1 --named-ports=http:8080Turn on autoscaling (changes the project)
- What it shows: 2 to 8 VMs, aiming for 80% of the load balancer capacity per VM.
- What to look for: Target size changing in command 2 as traffic changes.
gcloud compute instance-groups managed set-autoscaling kade-media-mig \ --region=asia-southeast1 --min-num-replicas=2 --max-num-replicas=8 \ --target-load-balancing-utilization=0.8 --cool-down-period=120 \ --scale-in-control=max-scaled-in-replicas=2,time-window=600Add the group to the load balancer (changes the project)
- What it shows: The load balancer health check, the backend service with the group as its backend, and a new
/media/*rule in the existing URL map (exported, edited, imported back). - What to look for:
get-healthon kade-media-backend shows each VM HEALTHY.
gcloud compute health-checks create http kade-media-hc --port=8080 \ --request-path=/healthz --check-interval=5sgcloud compute backend-services create kade-media-backend --global \ --load-balancing-scheme=EXTERNAL_MANAGED --protocol=HTTP --port-name=http \ --health-checks=kade-media-hc --connection-draining-timeout=60 \ --enable-logging --logging-sample-rate=1.0 --security-policy=kade-edge-policy --enable-cdngcloud compute backend-services add-backend kade-media-backend --global \ --instance-group=kade-media-mig --instance-group-region=asia-southeast1 \ --balancing-mode=RATE --max-rate-per-instance=80gcloud compute url-maps export kade-url-map --global --destination=kade-url-map.yaml# in pathMatchers → name: web → pathRules, add:# - paths: ["/media/*"]# service: https://www.googleapis.com/compute/v1/projects/kade-prod/global/backendServices/kade-media-backendgcloud compute url-maps import kade-url-map --global --source=kade-url-map.yamlStart a canary, then a full rolling update (changes the project)
- What it shows: First one VM on v2 alongside v1; when it looks good, everything moves to v2 with no capacity lost.
- What to look for: Command 1 showing the template per VM, and error ratio unchanged on the dashboard.
gcloud compute instance-groups managed rolling-action start-update kade-media-mig \ --region=asia-southeast1 --version=template=kade-media-tpl-v1 \ --canary-version=template=kade-media-tpl-v2,target-size=1 --max-surge=3 --max-unavailable=0gcloud compute instance-groups managed rolling-action start-update kade-media-mig \ --region=asia-southeast1 --version=template=kade-media-tpl-v2 --max-surge=3 --max-unavailable=0Roll back (changes the project)
- What it shows: The same command, pointing at the previous template. The old template was never changed, so this always works.
- What to look for: All VMs back on v1 in command 1.
gcloud compute instance-groups managed rolling-action start-update kade-media-mig \ --region=asia-southeast1 --version=template=kade-media-tpl-v1 --max-surge=3 --max-unavailable=0