Chapters

Load balancing 3: VMs behind the load balancer

Chapter 12.1 used Cloud Run as the backend, where Google creates, scales and heals instances for you. With VMs, you decide how many exist, how they are built, when they are replaced, and how a new version reaches them. A managed instance group (MIG) does that work for you, once you tell it the rules. This chapter covers those rules, and how the group plugs into the load balancer.

The front door · chapter 16 of 26 · 11 min read

VM or Cloud Run?

#Choose VMs (in a MIG) when…Choose Cloud Run when…
1The software needs OS-level setup: special libraries, drivers, a GPU, kernel settingsIt runs happily in a container
2Load is steady all day, so paying per VM-hour is cheaper than per requestLoad is spiky or often near zero; Cloud Run scales to zero
3Requests run long, or connections stay open for hours (WebSockets, streaming)Requests finish within Cloud Run's request timeout
4It needs a large local disk or memory cache that should survive between requestsEach request can stand alone
5You need control over the machine (OS version, agents, tuning)You want Google to own patching and scaling
What you take on with VMs: OS patching, image builds, the Ops Agent for metrics (chapter 16.1), and the MIG settings in this chapter. Both kinds can sit behind the same load balancer, chosen by the URL map.

The shape: template, group, load balancer

Instance templatekade-media-tpl-v1e2-standard-2 · imagesn-app · no external IPsa-kade-mediakade-media-mig · regional · asia-southeast1zone akade-media-x7k2(room to grow)zone bkade-media-p3fd(room to grow)zone c(room to grow)(room to grow)every new VM is builtfrom this recipeAutohealingrecreates broken VMsAutoscaler2 to 8 VMs with loadBackend servicekade-media-backend← from the LBsends traffic only tohealthy VMs in the group
#PieceJobKadé's value
1Instance templateThe recipe for every VM in the groupkade-media-tpl-v1
2Managed instance groupKeeps the right number of VMs from that recipe runningkade-media-mig, regional, asia-southeast1
3AutohealingRecreates a VM whose app stops answeringHTTP check /healthz, initial delay 180 s
4AutoscalerChanges the number of VMs with load2 to 8 VMs, load balancer usage target 80%
5Backend serviceConnects 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 templateKadé's valueWhy it matters
1Machine typee2-standard-2Size per VM; the autoscaler handles the count
2Boot imagekade-media-2026-09, a custom image with the app and Ops Agent already installedNew VMs start in seconds. Installing everything at boot makes scale-out slow and fragile
3Network interfacekade-vpc, sn-app, no external IPOne wrong template gives every future VM a public address (chapter 3)
4Service accountsa-kade-mediaFirewall rules target it (chapter 5.1), so new VMs are covered automatically
5MetadataA small startup script that reads config; OS Login inherited from the projectNever set enable-oslogin=FALSE here (chapter 6.2)
6Shielded VM, disk sizeOn; 50 GB balanced disk for the image cacheThe cache is rebuilt on a new VM; nothing on the disk must be precious

The group: zonal or regional

#Zonal MIGRegional MIG
1Where VMs runOne zoneSpread across zones in the region (up to three)
2A zone failsThe whole group is downThe others keep serving; the group rebuilds in the healthy zones
3Use forBatch work, testingAnything users depend on. Kadé's choice
MIG VMs get generated names like 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 checkAutohealing health check
1Set onThe backend serviceThe MIG
2When a VM fails itStop sending it traffic. The VM keeps runningDelete and recreate the VM from the template
3Should beQuick to react: a few secondsSlower and more patient: only for VMs that will not recover by themselves
4FirewallBoth 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:

What if
hangsautohealing recreates itkade-media-x7k2servingapp hungnew VM bootingLB traffic to itsent trafficremoved after ~10 sgroup size2 of 2 serving1 of 2 serving0 s30 s60 s90 s120 s150 s

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:

#SignalMeansGood for
1Load balancer usageRequests per VM against the capacity set on the backend serviceWeb backends behind a load balancer. Kadé's choice
2CPU utilizationAverage CPU across the groupCPU-bound work; can also be predictive, scaling before a daily peak
3A Cloud Monitoring metricAny metric, such as a queue's lengthWorkers pulling jobs from a queue
4SchedulesA minimum size during set hoursKnown peaks: a sale starting at 8 pm
#SettingKadé's valueWhy
1Minimum VMs2One VM per zone at least, so a zone failure or a single bad VM never empties the group
2Maximum VMs8A ceiling for cost and for the NAT ports and database connections each VM uses (chapter 7)
3Initialization period120 sHow 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
4Scale-in controlsAt most 2 VMs removed per 10 minutesStops a short dip from removing capacity that the next spike needs
The autoscaler also waits about 10 minutes of lower load before scaling in, on purpose. Scaling out is fast; scaling in is cautious.
What if
00:0006:0012:0018:0024:000200400600requests per seconddemandcapacity (VMs × 80)

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:

#SettingMeansKadé's value
1Max surgeHow many extra VMs may exist above the target size during the update3 (one per zone; a regional MIG needs 0 or at least the number of zones)
2Max unavailableHow many VMs may be out of service at once0: never go below full capacity
3Minimal actionREPLACE (new VM) or RESTARTREPLACE: a new template needs new VMs

Step through an update. Each square is one VM, labelled with its template:

Step

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:

LINK 1Forwarding rulekade-https-rule34.120.88.10:443LINK 2Target proxykade-https-proxyTLS ends hereLINK 3URL mapkade-url-mapwww…/media/* →LINK 4Backend servicekade-media-backendRATE 80/VM · Armor · CDNLINK 5Instance groupkade-media-mignamed port http:8080

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 settingKadé's valueEffect
1Port namehttpMatches the group's named port http:8080
2Balancing modeRATE, 80 requests per second per VM"Full" means 80 rps; the autoscaler targets 80% of it
3Capacity scaler1.0Set to 0 to drain a whole group without deleting it, for example before replacing it
4Health checkkade-media-hc: HTTP /healthz, 5 sThe quick one from section 05
5Connection draining60 sVMs leaving the group finish their requests (chapter 12.1 section 05)
6Cloud Armor, CDN, loggingkade-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:

#NeedHow, for a MIGChapter
1No public addressTemplate without an external IP; organization policy as a safety net3, 17
2Health checks reach the appFirewall rule from Google's ranges to service account sa-kade-media on 80805.1
3Outgoing internet (updates, APIs)Cloud NAT covering sn-app; check ports at maximum size7
4Google APIs (Cloud Storage for originals)Private Google Access on sn-app9
5Admin SSHIAP + OS Login, inherited from project metadata6
6Metrics and logs from inside the VMOps Agent baked into the image16.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: RUNNING and HEALTHY. VMs stuck in RECREATING again and again mean a boot loop (section 05).
gcloud compute instance-groups managed list-instances kade-media-mig \  --region=asia-southeast1

See 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-balanced

Create the regional group with autohealing (changes the project)

  • What it shows: Two VMs spread across the region's zones, recreated if /healthz fails, 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:8080

Turn 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=600

Add 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-health on 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.yaml

Start 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=0

Roll 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

Spotted a mistake, or something unclear? Suggest an edit on GitHub

See it broken

Harbour is a platform built wrong on purpose. This defect is this chapter's idea, left undone: what it breaks, how you would find it, and the change that closes it.

  1. D13
    TCP health check on a web backend

    mediumcloses in phase 5, Egress and load balancer

    Goes with Two health checks with two different jobs