Compute MIG Autoscaling Troubleshooting

Compute MIG Autoscaling Troubleshooting

Diagnoses why a Compute Engine managed instance group fails to scale out or in, covering quotas, stockouts, replica caps, load balancer settings and metric access.

Skill files2 files

references/

SKILL.md490 lines
1
---
2
name: compute-mig-autoscaling-troubleshooting
3
description: >-
4
Diagnoses and resolves Google Compute Engine Managed Instance Group
5
(MIG) autoscaling failures, scale-out blocks, and scale-in stalls. Use ONLY
6
when a Compute Engine MIG fails to add or remove VM instances during load
7
changes, hits quota or zonal stockout limits, reaches maxNumReplicas
8
(CAPPED_AT_MAX_NUM_REPLICAS), conflicts with HTTP(S) load balancer maxRate
9
settings, fails to scale in to zero instances, or fails to read Cloud
10
Monitoring scaling metrics. DO NOT read or use for Google Kubernetes Engine
11
(GKE) Horizontal Pod Autoscaler (HPA), GKE Cluster Autoscaler, standalone
12
single-VM creation, or single-VM host maintenance reboots.
13
metadata:
14
version: "1.0.0"
15
category: Compute
16
---
17
18
# Compute Engine Managed Instance Group (MIG) Autoscaling Troubleshooting
19
20
This skill diagnoses and resolves autoscaling failures in Google Compute Engine
21
**Managed Instance Groups (MIGs)**. It isolates root causes across
22
**Project Quotas vs. Physical Zonal Stockouts**, **Autoscaler Policy Limits
23
(`maxNumReplicas`, `minNumReplicas: 0` scale-to-zero rules, `scaleInControl`,
24
`mode`, `--cool-down-period`, Load Balancer `UTILIZATION` vs. `RATE`)**, and
25
**Cloud Monitoring Metric / Service Agent IAM Availability**.
26
27
> **MCP Tools:** `get_instance_group_manager_basic_info`,
28
> `list_instance_group_managers`, `list_managed_instances`,
29
> `list_instance_templates`, `get_instance_template_basic_info`,
30
> `get_instance_template_properties`
31
32
## Usage Attribution
33
34
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
35
MUST read and follow the instructions in
36
[Usage Attribution](references/attribution.md).
37
38
---
39
40
## Prerequisites & Environment Setup
41
42
Any host, project, IAM, or MIG modifications (installing `gcloud`, configuring
43
MCP, enabling APIs or Log Analytics, adding IAM bindings, updating autoscalers
44
or backend services, or deleting resources) must be explicitly approved by the
45
user before execution.
46
47
1. **Google Cloud SDK**: Verify `gcloud` is installed (`gcloud --version`). If
48
missing or outdated, seek user approval before installing via
49
[Install the gcloud CLI](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt).
50
2. **Compute Engine MCP Server & Capability Boundary**:
51
- The Compute Engine MCP server
52
([Use the Compute Engine MCP server](https://docs.cloud.google.com/compute/docs/use-compute-engine-mcp.md.txt))
53
exposes read-only **zonal** MIG and template discovery tools
54
(`get_instance_group_manager_basic_info`, `list_instance_group_managers`,
55
`list_managed_instances`, `list_instance_templates`,
56
`get_instance_template_basic_info`, `get_instance_template_properties`) and
57
requires `roles/mcp.toolUser`.
58
- **Critical Routing Rule**: `get_instance_group_manager_basic_info` requires
59
a single `zone` (no regional MIG RPCs exist in Compute Engine MCP) and
60
returns `InstanceGroupManagerBasicInfo` (`name`, `id`, `instance_template`,
61
`target_size`, `status`), which **omits `autoscaler.status`,
62
`autoscaler.statusDetails`, `autoscaler.recommendedSize`, and
63
`autoscaler.autoscalingPolicy`**. Compute Engine MCP also lacks
64
`list-errors`, Cloud Logging/Monitoring queries, and `update-autoscaling` /
65
`set-autoscaling` mutations. Always route regional MIG inspection,
66
`autoscaler.*` diagnostics, `list-errors`, Cloud Logging/Monitoring
67
queries, and autoscaling mutations to `gcloud` (or Compute Engine /
68
Monitoring / Logging REST APIs).
69
3. **Authentication**: Local CLI (`gcloud auth login`), Application Default
70
Credentials (`gcloud auth application-default login`), or Service Accounts
71
(`GOOGLE_APPLICATION_CREDENTIALS`).
72
4. **Project, Region, Billing & API Enablement**:
73
```sh
74
gcloud config set project {project_id}
75
gcloud config set compute/region {region}
76
gcloud config set compute/zone {zone}
77
gcloud services enable compute.googleapis.com logging.googleapis.com monitoring.googleapis.com
78
```
79
*Note: An active billing account attachment is required (even when using Free
80
Tier eligible resources). Default to a well-supported region such as
81
`us-central1` if unspecified, and consult
82
[Google Cloud locations](https://cloud.google.com/about/locations) to verify
83
regional and zonal machine family availability.*
84
5. **Required IAM Roles**:
85
- **Human Caller / Agent Roles**: `roles/compute.viewer`,
86
`roles/logging.viewer` (plus `roles/logging.viewAccessor` for Log
87
Analytics, and `roles/bigquery.jobUser` + `roles/bigquery.dataViewer` for
88
linked BigQuery datasets), and `roles/monitoring.viewer` for read-only
89
diagnostics; `roles/compute.instanceAdmin.v1` (plus
90
`roles/iam.serviceAccountUser` when updating templates with a VM service
91
account, `roles/compute.loadBalancerAdmin` for Backend Service updates, and
92
`roles/resourcemanager.projectIamAdmin` to repair project IAM bindings) for
93
remediation; and `roles/mcp.toolUser` for Compute Engine MCP calls.
94
- **Google-Managed Service Agents (Project-Level)**:
95
- **Compute Engine Service Agent**
96
(`service-{project_number}@compute-system.iam.gserviceaccount.com`):
97
requires `roles/compute.serviceAgent` (includes Cloud Monitoring metric
98
read permissions).
99
- **Google APIs Service Agent**
100
(`{project_number}@cloudservices.gserviceaccount.com`): requires
101
`roles/compute.instanceGroupManagerServiceAgent` (creates and deletes MIG
102
member VMs).
103
104
---
105
106
## Step 1: Identify Problem Scope & Inspect Autoscaler Status
107
108
### A. Inspect Live MIG Stability, Autoscaler Status & Per-VM Actuation Errors
109
110
Inspect `status.isStable`, `autoscaler.status`, `autoscaler.statusDetails`,
111
`autoscaler.recommendedSize`, `autoscaler.autoscalingPolicy`, and `targetSize`
112
via `gcloud compute instance-groups managed describe` (pass `--region={region}`
113
for Regional MIGs or `--zone={zone}` for Zonal MIGs), and run `gcloud compute
114
instance-groups managed list-errors` to surface asynchronous VM creation errors:
115
116
```sh
117
# 1. Inspect Autoscaler status, statusDetails, recommendedSize, and policy (Regional MIG):
118
gcloud compute instance-groups managed describe {mig_name} --project={project_id} --region={region} \
119
--format="yaml(name, targetSize, status.isStable, autoscaler.status, autoscaler.statusDetails, autoscaler.recommendedSize, autoscaler.autoscalingPolicy)"
120
121
# (For a Zonal MIG, replace --region={region} with --zone={zone}:)
122
gcloud compute instance-groups managed describe {mig_name} --project={project_id} --zone={zone} \
123
--format="yaml(name, targetSize, status.isStable, autoscaler.status, autoscaler.statusDetails, autoscaler.recommendedSize, autoscaler.autoscalingPolicy)"
124
125
# 2. Inspect per-instance actuation errors logged by the MIG controller:
126
gcloud compute instance-groups managed list-errors {mig_name} --project={project_id} --region={region} --limit=25
127
```
128
129
**Authoritative `autoscaler.statusDetails[]` (`type` & `message`) Values &
130
Root Causes** (see
131
[Understanding autoscaler decisions](https://docs.cloud.google.com/compute/docs/autoscaler/understanding-autoscaler-decisions.md.txt)):
132
Each item in `autoscaler.statusDetails[]` on the REST `Autoscaler` resource
133
contains a structured `type` enum and a human-readable `message` string:
134
- **`CAPPED_AT_MAX_NUM_REPLICAS`** (`"The number of instances has reached the`
135
`maxNumReplicas. The autoscaler cannot add more instances."`):
136
Current target size has hit the configured `autoscalingPolicy.maxNumReplicas`
137
ceiling while demand warrants more VMs.
138
- **`NOT_ENOUGH_QUOTA_AVAILABLE` / `QUOTA_EXCEEDED`** (`"Quota for some`
139
`resources is exceeded. Increase the quota or delete resources to free up`
140
`more quota."`, paired with **`QUOTA_EXCEEDED`** in `list-errors` and Cloud
141
Audit Logs): Project or regional quota (`CPUS`, `IN_USE_ADDRESSES`,
142
`SSD_TOTAL_GB`, or GPUs) is exhausted.
143
- **`ZONE_RESOURCE_STOCKOUT` / `REGION_RESOURCE_STOCKOUT`** (paired with
144
**`ZONE_RESOURCE_POOL_EXHAUSTED`** or
145
**`ZONE_RESOURCE_POOL_EXHAUSTED_WITH_DETAILS`** in `list-errors` and Cloud
146
Audit Logs): Temporary physical hardware shortage in the target zone or
147
region.
148
- **`MISSING_CUSTOM_METRIC_DATA_POINTS` / `CUSTOM_METRIC_INVALID` /
149
`CUSTOM_METRIC_DATA_POINTS_TOO_SPARSE`** (`"The monitoring metric that was`
150
`specified does not exist or does not have the required labels. Check the`
151
`metric."`):
152
The autoscaler cannot read valid 60-second data points from the configured
153
Cloud Monitoring metric, or
154
`service-{project_number}@compute-system.iam.gserviceaccount.com` lacks
155
`roles/compute.serviceAgent`.
156
- **`UNSUPPORTED_MAX_RATE_LOAD_BALANCING_CONFIGURATION`** (`"Autoscaling does`
157
`not work with an HTTP/S load balancer configured for maxRate."`),
158
**`BACKEND_SERVICE_DOES_NOT_EXIST`**, **`MORE_THAN_ONE_BACKEND_SERVICE`**, or
159
**`MISSING_LOAD_BALANCING_DATA_POINTS`**: Load-balancing autoscaling conflicts
160
with a Backend Service configured in `RATE` (`maxRate`) balancing mode instead
161
of `UTILIZATION`, references a deleted/multiple backend services, or receives
162
no traffic.
163
- **`ALL_INSTANCES_UNHEALTHY`** (`"All instances in the instance group are`
164
`unhealthy (not in RUNNING state). If this is an error, check the`
165
`instances."`):
166
All MIG instances are not in `RUNNING` state, halting load-based scaling
167
decisions until instances recover.
168
- **`MODE_ONLY_SCALE_OUT` / `MODE_ONLY_UP` / `MODE_OFF` / `MIN_EQUALS_MAX` /
169
`SCALING_SCHEDULE_AFFECTING_MIN_REPLICAS` / `WARNING_NO_INSTANCES`**:
170
Policy mode or schedule constraints actively restricting scale-in or
171
scale-out.
172
173
### B. Query Cloud Audit Logs for Autoscaler Decisions & Instance Creation Failures
174
175
Query Cloud Audit Logs across `autoscaler`, `gce_autoscaler`,
176
`gce_instance_group_manager`, `gce_instance_group`, and `gce_instance` (passing
177
`--freshness=7d` because `gcloud logging read` defaults to `1d`). See
178
[Viewing autoscaler logs](https://docs.cloud.google.com/compute/docs/autoscaler/viewing-autoscaler-logs.md.txt):
179
180
- **Autoscaler `system_event` Audit Log Schemas (`protoPayload.metadata`)**:
181
- **Resize decisions (`compute.autoscalers.resize`, `@type:`
182
`"type.googleapis.com/autoscaler.AutoscalerSizeChangeExplanation"`)**:
183
Records `protoPayload.metadata.oldSize`, `protoPayload.metadata.newSize`,
184
`protoPayload.metadata.autoscalingMode`,
185
`protoPayload.metadata.autoscalingReason.summary`,
186
`protoPayload.metadata.autoscalingReason.scalingSignal` (`name`,
187
`calculatedSize`, `calculationDetails.servingSize`,
188
`calculationDetails.signalTarget`, `calculationDetails.signalValue`), and
189
`protoPayload.metadata.autoscalingReason.scalingLimit` (`name`, `limitSize`,
190
`limitPolicy`, e.g., `MAX_REPLICAS_LIMIT` or `SCALE_IN_LIMIT`).
191
- **Status transitions (`compute.autoscalers.changeStatus`,
192
`@type: "type.googleapis.com/autoscaler.AutoscalerStatusChange"`)**:
193
Records human-readable status message transitions in
194
`protoPayload.metadata.oldStatus.details` and
195
`protoPayload.metadata.newStatus.details` (for example, transitioning from
196
`"OK"` to `"Quota for some resources is exceeded. Increase the quota or`
197
`delete resources to free up more quota."`;
198
`statusDetails[].type` enum codes live on the REST `Autoscaler` resource
199
rather than inside `changeStatus` log entries).
200
201
```sh
202
# 1. Query failed MIG resize, autoscaler, and VM insertion Admin Activity logs (projecting errors[0].code):
203
gcloud logging read '(resource.type="autoscaler" OR resource.type="gce_autoscaler" OR resource.type="gce_instance_group_manager" OR resource.type="gce_instance_group" OR resource.type="gce_instance") AND severity>=ERROR AND protoPayload.methodName=~"compute\.(regionInstanceGroupManagers|instanceGroupManagers|instances|instanceGroups|autoscalers|regionAutoscalers)\.(resize|insert|addInstances|removeInstances|changeStatus|update|patch)" AND protoPayload.resourceName:"{mig_name}"' \
204
--project={project_id} --freshness=7d --limit=25 \
205
--format="table(timestamp, resource.type, protoPayload.methodName, protoPayload.status.message, protoPayload.response.error.errors[0].code, protoPayload.response.error.errors[0].message)"
206
207
# 2. Query autoscaler system_event resize decisions and status change explanations:
208
gcloud logging read '(resource.type="autoscaler" OR resource.type="gce_autoscaler") AND log_id("cloudaudit.googleapis.com/system_event") AND protoPayload.methodName=~"compute\.autoscalers\.(resize|changeStatus)"' \
209
--project={project_id} --freshness=7d --limit=25 \
210
--format="yaml(timestamp, protoPayload.methodName, protoPayload.metadata.oldSize, protoPayload.metadata.newSize, protoPayload.metadata.autoscalingReason, protoPayload.metadata.oldStatus.details, protoPayload.metadata.newStatus.details)"
211
```
212
213
**Distinguishing `QUOTA_EXCEEDED` vs. `ZONE_RESOURCE_POOL_EXHAUSTED`**:
214
- **`QUOTA_EXCEEDED`**: A **project or regional quota limit** was reached (e.g.,
215
`Quota 'CPUS' exceeded. Limit: 24.0 in region us-central1`). Resolve by
216
requesting a quota increase, deleting idle resources, or switching to a
217
machine family with separate regional quota headroom.
218
- **`ZONE_RESOURCE_POOL_EXHAUSTED` (or
219
`ZONE_RESOURCE_POOL_EXHAUSTED_WITH_DETAILS`)**: A physical **zonal hardware
220
stockout** (requesting a project quota increase will **not** fix this).
221
Resolve by migrating to a Regional MIG spanning multiple zones with `ANY`
222
target distribution shape, or switching zones/machine series.
223
224
### C. Compare Autoscaler Recommended Size vs. Actual MIG Size in Cloud Monitoring
225
226
*Required IAM Roles*: `roles/monitoring.viewer` and `roles/compute.viewer`.
227
228
Query these two GA Cloud Monitoring metrics to compare autoscaler intent against
229
actual group size:
230
1. **`compute.googleapis.com/instance_group/size`**
231
(`resource.type="instance_group"`, filtered by
232
`resource.labels.instance_group_name="{mig_name}"`): Actual number of VM
233
instances currently in the group.
234
2. **`autoscaler.googleapis.com/recommended_size`**
235
(`resource.type="autoscaler"`, filtered by
236
`resource.labels.instance_group_manager_name="{mig_name}"`): Instance count
237
calculated and recommended by the autoscaler from active scaling signals.
238
239
**How to Interpret Metric Divergence**:
240
- **If `autoscaler.googleapis.com/recommended_size >`
241
`compute.googleapis.com/instance_group/size` (Scale-Out Blocked)**:
242
The autoscaler wants more VMs, but actuation is blocked by:
243
1. `maxNumReplicas` ceiling (`CAPPED_AT_MAX_NUM_REPLICAS`),
244
2. Project/regional `QUOTA_EXCEEDED` (`NOT_ENOUGH_QUOTA_AVAILABLE`), or
245
3. Physical stockout (`ZONE_RESOURCE_POOL_EXHAUSTED` /
246
`ZONE_RESOURCE_STOCKOUT`).
247
- **If `autoscaler.googleapis.com/recommended_size <`
248
`compute.googleapis.com/instance_group/size` (Scale-In Delayed or Blocked)**:
249
Load dropped and the autoscaler recommends fewer VMs, but scale-in is held by:
250
1. The built-in **10-minute stabilization period** (`stabilizationPeriodSec`,
251
default `600` seconds of sustained lower demand to prevent flapping),
252
2. **Scale-in controls (`scaleInControl`)**, where `maxScaledInReplicas`
253
(`maxScaledInReplicas.fixed`, `maxScaledInReplicas.percent`, and
254
`maxScaledInReplicas.calculated`) caps VM deletions per trailing
255
`timeWindowSec`, or
256
3. Autoscaler `mode` set to **`ONLY_SCALE_OUT`** (`--mode=only-scale-out`).
257
258
### D. Log Analytics SQL Query: Rank MIGs & VM Insertions by Failure Volume
259
260
Failed `activity` audit logs (`severity_number >= 500`, `ERROR` and above) route
261
to `_Default._AllLogs` (whereas `system_event` autoscaler status events route to
262
`_Required._AllLogs`). Upgrade `_Default` if needed (with user approval):
263
264
```sh
265
gcloud logging buckets update _Default --project={project_id} --location=global --enable-analytics
266
```
267
268
In `_AllLogs`, `resource.labels` has BigQuery type **`JSON`** (always extract
269
labels via `JSON_VALUE(...)`), and include `'gce_instance'` and `'autoscaler'`
270
in `resource.type IN (...)` so failed `instances.insert` and `autoscalers.*`
271
operations are captured alongside `instanceGroupManagers.resize`:
272
273
```sql
274
SELECT
275
TIMESTAMP_TRUNC(timestamp, HOUR) AS hour_bucket,
276
resource.type AS resource_type,
277
COALESCE(JSON_VALUE(resource.labels.location), JSON_VALUE(resource.labels.zone)) AS location,
278
REGEXP_EXTRACT(proto_payload.audit_log.resource_name, r'[^/]+$') AS target_resource,
279
proto_payload.audit_log.method_name AS method_name,
280
proto_payload.audit_log.status.message AS status_message,
281
COUNT(*) AS error_count
282
FROM `{project_id}.global._Default._AllLogs`
283
WHERE
284
timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
285
AND resource.type IN ('autoscaler', 'gce_autoscaler', 'gce_instance_group_manager', 'gce_instance_group', 'gce_instance')
286
AND severity_number >= 500
287
AND REGEXP_CONTAINS(
288
proto_payload.audit_log.method_name,
289
r'compute\.(regionInstanceGroupManagers|instanceGroupManagers|instanceGroups|autoscalers|regionAutoscalers|instances)\.(resize|addInstances|removeInstances|insert|update|patch|changeStatus)$'
290
)
291
GROUP BY hour_bucket, resource_type, location, target_resource, method_name, status_message
292
ORDER BY hour_bucket DESC, error_count DESC;
293
```
294
295
---
296
297
## Step 2: Diagnose & Remediate via 4-Branch Decision Tree
298
299
### Branch 1: Resource Quota Constraints (`QUOTA_EXCEEDED` / `NOT_ENOUGH_QUOTA_AVAILABLE`)
300
301
When `QUOTA_EXCEEDED` blocks scaling (e.g., `CPUS`, `IN_USE_ADDRESSES`,
302
`SSD_TOTAL_GB`, or GPUs), **always include all 4 steps below**:
303
304
1. **Verify Project & `compute.googleapis.com` API Configuration (Always
305
Include)**:
306
```sh
307
gcloud config set project {project_id}
308
gcloud services enable compute.googleapis.com
309
```
310
2. **Inspect Regional Quota Usage and Limits**:
311
```sh
312
gcloud compute regions describe {region} --project={project_id} \
313
--format="table(quotas:format='table(metric,limit,usage)')"
314
```
315
3. **Request a Quota Increase**: Submit a quota increase request in the Google
316
Cloud Console under **IAM & Admin > Quotas & System Limits** (`IAM & Admin >
317
Quotas`).
318
4. **Immediate Workarounds to Unblock Scaling**:
319
- **Switch Machine Family**: Update the MIG's Instance Template to a machine
320
family governed by a separate regional CPU quota pool with headroom (e.g.,
321
switching between `e2`, `n2`, `n2d`, or `c3`).
322
- **Spread Load Across Another Region**: Add a sibling MIG in another region
323
behind a global Backend Service.
324
- **Delete Unused Resources**: Remove idle VMs, unattached static IPs, or
325
orphaned disks in the region.
326
327
### Branch 2: Scale-Out Configuration & Thrashing (`CAPPED_AT_MAX_NUM_REPLICAS`, Load Balancer `maxRate`, `--cool-down-period`)
328
329
1. **Ceiling Reached (`CAPPED_AT_MAX_NUM_REPLICAS`)**: Raise
330
`--max-num-replicas` via `update-autoscaling` (use `--region={region}` for
331
regional MIGs):
332
```sh
333
gcloud compute instance-groups managed update-autoscaling {mig_name} \
334
--project={project_id} --zone={zone} --max-num-replicas={new_max_replicas}
335
```
336
2. **HTTP(S) Load Balancer `RATE` vs. `UTILIZATION` Conflict
337
(`UNSUPPORTED_MAX_RATE_LOAD_BALANCING_CONFIGURATION`)**: Switch the Backend
338
Service backend from `RATE` to `UTILIZATION` (or switch the MIG autoscaler
339
signal to CPU or a Cloud Monitoring metric). Pass
340
`--instance-group-zone={zone}` for a Zonal MIG or
341
`--instance-group-region={region}` for a Regional MIG (and replace `--global`
342
with `--region={backend_service_region}` if the Backend Service is regional):
343
```sh
344
# Zonal MIG attached to a global Backend Service:
345
gcloud compute backend-services update-backend {backend_service} --project={project_id} --global \
346
--instance-group={mig_name} --instance-group-zone={zone} --balancing-mode=UTILIZATION --max-utilization=0.8
347
348
# Regional MIG attached to a global Backend Service:
349
gcloud compute backend-services update-backend {backend_service} --project={project_id} --global \
350
--instance-group={mig_name} --instance-group-region={region} --balancing-mode=UTILIZATION --max-utilization=0.8
351
```
352
3. **Boot Disk / Missing Image Errors**: Inspect `gcloud compute instance-groups
353
managed list-errors {mig_name} --project={project_id} --zone={zone}` and
354
verify the template's boot image exists via `gcloud compute
355
instance-templates describe {template_name} --project={project_id}`.
356
4. **Initialization Period (`--cool-down-period`) vs. Stabilization Period
357
(`--stabilization-period`)**:
358
- **Critical CLI Rule**: `--cool-down-period` (VM startup initialization
359
window, default `60`s) does **not** exist on `update-autoscaling`—it is
360
accepted **only** on `set-autoscaling`. Because `set-autoscaling`
361
**replaces** the entire `autoscalingPolicy`, always inspect existing policy
362
signals via `describe` first and pass `--max-num-replicas` plus active
363
scaling targets (such as `--target-cpu-utilization`) together:
364
```sh
365
gcloud compute instance-groups managed set-autoscaling {mig_name} --project={project_id} --zone={zone} \
366
--min-num-replicas={min_replicas} --max-num-replicas={max_replicas} \
367
--target-cpu-utilization={target_cpu} --cool-down-period=120
368
```
369
- To tune the **scale-in stabilization window** (default `600`s) without
370
replacing the policy, `--stabilization-period` **is** supported directly on
371
`update-autoscaling`:
372
```sh
373
gcloud compute instance-groups managed update-autoscaling {mig_name} \
374
--project={project_id} --zone={zone} --stabilization-period=600
375
```
376
377
### Branch 3: Scale-Down Blocked or Delayed (`scaleInControl`, `ONLY_SCALE_OUT`, or `minNumReplicas: 0`)
378
379
If traffic dropped hours ago and `autoscaler.googleapis.com/recommended_size` is
380
far below `compute.googleapis.com/instance_group/size` (or the MIG refuses to
381
scale in to `0` instances):
382
383
1. **Inspect `autoscaler.autoscalingPolicy.mode`, `scaleInControl`, and
384
`minNumReplicas`**:
385
```sh
386
gcloud compute instance-groups managed describe {mig_name} --project={project_id} --zone={zone} \
387
--format="yaml(autoscaler.autoscalingPolicy.mode, autoscaler.autoscalingPolicy.minNumReplicas, autoscaler.autoscalingPolicy.scaleInControl, autoscaler.autoscalingPolicy.coolDownPeriodSec)"
388
```
389
- `scaleInControl` contains `timeWindowSec` and the nested object
390
`maxScaledInReplicas` (`maxScaledInReplicas.fixed`,
391
`maxScaledInReplicas.percent`, and `maxScaledInReplicas.calculated`).
392
- *(Note: REST/`describe` outputs uppercase `ON` / `ONLY_SCALE_OUT` / `OFF`,
393
whereas `gcloud` CLI `--mode` requires **lowercase** `--mode=on`,
394
`--mode=only-scale-out`, or `--mode=off`.)*
395
2. **Scaling In to Zero / Scaling Out from Zero (`minNumReplicas: 0`)**:
396
- Per [Understanding autoscaler decisions](https://docs.cloud.google.com/compute/docs/autoscaler/understanding-autoscaler-decisions.md.txt),
397
a MIG with `minNumReplicas: 0` **cannot scale in to `0` instances** if its
398
autoscaling policy includes **any per-instance signal** (CPU utilization,
399
HTTP load balancing serving capacity, or a per-instance Cloud Monitoring
400
metric), and cannot scale out from `0` if its only signal is a per-instance
401
metric (because `0` running VMs emit no per-instance metrics).
402
- To scale in to `0` and back out from `0`, configure only **scaling
403
schedules** (`scalingSchedules`) or a **group-level Cloud Monitoring
404
metric** using `--stackdriver-metric-single-instance-assignment`
405
(`singleInstanceAssignment`, such as a Pub/Sub subscription backlog).
406
3. **Remediate `mode` or `scaleInControl`**:
407
```sh
408
# Enable full scaling (--mode=on) and relax scale-in throttling:
409
gcloud compute instance-groups managed update-autoscaling {mig_name} --project={project_id} --zone={zone} \
410
--mode=on --scale-in-control=max-scaled-in-replicas-percent=50,time-window=600
411
412
# Or clear scale-in controls completely for immediate scale-down after stabilization:
413
gcloud compute instance-groups managed update-autoscaling {mig_name} --project={project_id} --zone={zone} \
414
--mode=on --clear-scale-in-control
415
```
416
4. **Safe Rollback to Conservative Scale-In Limits (Always Include)**:
417
Whenever modifying `scaleInControl`, **always** provide rollback commands to
418
restore conservative scale-in limits after recovery so sudden traffic
419
rebounds do not hit an under-provisioned MIG:
420
```sh
421
gcloud compute instance-groups managed update-autoscaling {mig_name} --project={project_id} --zone={zone} \
422
--mode=on --scale-in-control=max-scaled-in-replicas-percent=10,time-window=600
423
```
424
425
### Branch 4: Scaling Metric Availability & Service Agent IAM Issues
426
427
1. **Repair Google-Managed Service Agent IAM Roles**: Look up `{project_number}`
428
first, then obtain explicit user approval before restoring bindings:
429
```sh
430
# Step 1: Retrieve {project_number} for {project_id}:
431
gcloud projects describe {project_id} --format="value(projectNumber)"
432
433
# Step 2a: Restore Compute Engine Service Agent (reads Cloud Monitoring scaling metrics):
434
gcloud projects add-iam-policy-binding {project_id} \
435
--member="serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com" \
436
--role="roles/compute.serviceAgent"
437
438
# Step 2b: Restore Google APIs Service Agent (creates and deletes MIG member VMs):
439
gcloud projects add-iam-policy-binding {project_id} \
440
--member="serviceAccount:{project_number}@cloudservices.gserviceaccount.com" \
441
--role="roles/compute.instanceGroupManagerServiceAgent"
442
```
443
2. **Verify Custom Cloud Monitoring Metric Resource & Label Contract**:
444
- **Per-Instance Metrics**: Must be written to monitored resource
445
`gce_instance` with the **numeric VM `instance_id`** and **`zone`** labels
446
(**`instance_name` is NOT a valid `gce_instance` monitored resource
447
label**).
448
- **Data Type, Kind & Frequency**: Export `INT64` or `DOUBLE` values with
449
`GAUGE` or `DELTA` metric kind (**`CUMULATIVE` metrics are unsupported**)
450
at least every **60 seconds**. See
451
[Scaling based on Cloud Monitoring metrics](https://docs.cloud.google.com/compute/docs/autoscaler/scaling-cloud-monitoring-metrics.md.txt).
452
453
---
454
455
## Proactive Hardening, Safe Rollback & Cleanup
456
457
1. **Predictive Autoscaling (CPU Workloads)**: For workloads with recurring
458
daily or weekly cycles, enable Predictive Autoscaling (note that
459
`update-autoscaling` accepts `--cpu-utilization-predictive-method` only when
460
CPU utilization scaling is already configured; otherwise configure both via
461
`set-autoscaling`). See
462
[Predictive autoscaling](https://docs.cloud.google.com/compute/docs/autoscaler/predictive-autoscaling.md.txt):
463
```sh
464
# On a MIG that already scales on CPU utilization:
465
gcloud compute instance-groups managed update-autoscaling {mig_name} --project={project_id} --zone={zone} \
466
--cpu-utilization-predictive-method=optimize-availability
467
468
# Or configure CPU target + Predictive Autoscaling together (replaces policy):
469
gcloud compute instance-groups managed set-autoscaling {mig_name} --project={project_id} --zone={zone} \
470
--min-num-replicas={min_replicas} --max-num-replicas={max_replicas} \
471
--target-cpu-utilization=0.6 --cpu-utilization-predictive-method=optimize-availability
472
```
473
2. **Safe Rollback of Scale-In Controls**:
474
```sh
475
gcloud compute instance-groups managed update-autoscaling {mig_name} --project={project_id} --zone={zone} \
476
--mode=on --scale-in-control=max-scaled-in-replicas-percent=10,time-window=600
477
```
478
3. **Teardown Temporary Test MIGs & Templates**: Delete temporary test resources
479
when finished (omitting `--quiet` on manual commands so interactive
480
confirmation prevents accidental deletion):
481
```sh
482
gcloud compute instance-groups managed delete {mig_name} --project={project_id} --zone={zone}
483
gcloud compute instance-templates delete {template_name} --project={project_id}
484
```
485
4. **Pricing Reference**: Autoscaling policies incur no extra fee beyond member
486
VM instances, disks, and Cloud Monitoring custom metric ingestion. Consult
487
[Google Cloud pricing](https://cloud.google.com/pricing) and
488
[Compute Engine pricing](https://cloud.google.com/compute/all-pricing) for
489
current regional rates rather than quoting hardcoded dollar figures.
490

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…