GKE HPA 扩缩容故障排查
gke-workload-scaling-troubleshooting
诊断 GKE HorizontalPodAutoscaler (HPA) 故障——指标显示为 <unknown>、FailedGetResourceMetric / FailedGetScale / FailedComputeMetricsReplicas 事件、Pod 缺少 resource requests、自定义/外部指标管道故障(FailedGetExternalMetric / FailedGetCustomMetric、指标适配器不可用、控制平面防火墙阻断适配器)、HPA 无法扩容或缩容(容差 / 稳定窗口 / 速率指标不可用)、缩容至零及从零扩容的问题,以及大型集群中 HPA 反应迟缓。当 HPA 未按预期对工作负载进行扩缩容或报告指标错误时使用。不用于配置或编写新的 HPA/VPA 对象或扩缩容最佳实践(请参阅 gke-workload-scaling 技能),也不用于 Cluster Autoscaler / 节点池容量规划。
- License 许可
- Apache-2.0
- 所属仓库
- google/skills
- 最近更新
- 2026-11-14
- Stars
- ★ 2.4w
- Forks
- 2.0k
01 前言 Front Matter
- name
- gke-workload-scaling-troubleshooting
- metadata
- { "version": "1.0.1", "category": "Containers" }
- description
- Diagnoses GKE HorizontalPodAutoscaler (HPA) failures — metrics showing as <unknown>, FailedGetResourceMetric / FailedGetScale / FailedComputeMetricsReplicas events, missing Pod resource requests, custom/external metrics-pipeline breakage (FailedGetExternalMetric / FailedGetCustomMetric, unavailable metrics adapter, control-plane firewall blocking the adapter), HPA that won't scale up or down (tolerance / stabilization window / unavailable rate metrics), scale-to/from-zero problems, and slow HPA reaction on large clusters. Use when an HPA isn't scaling a workload as expected or reports metric errors. Don't use for configuring or authoring new HPA/VPA objects or scaling best practices (see the gke-workload-scaling skill), or for Cluster Autoscaler / node-pool sizing.
02 资源文件 1
- 参考文档references/attribution.md1.9 KB
03 SKILL.md 正文
GKE Workload Scaling Troubleshooting Skill
Use this skill to systematically diagnose and resolve HorizontalPodAutoscaler
(HPA) failures on GKE — metrics reported as <unknown>, FailedGet* events,
missing resource requests, custom/external metrics-pipeline breakage, HPA that
refuses to scale up or down, scale-to/from-zero issues, and slow HPA reaction on
large clusters. This skill operates non-interactively and enforces a read-only
diagnostics boundary before proposing manifest or configuration corrections.
For configuring HPA/VPA objects and scaling best practices, use the
gke-workload-scalingskill instead. This skill focuses on failure diagnosis.
Attribution
MUST READ: Before executing any gcloud, REST API, or MCP command, you
MUST read Usage Attribution. For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix gcloud with
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:gke-workload-scaling-troubleshooting)"
and append agent-skills/1.0 (skill:gke-workload-scaling-troubleshooting) to User-Agent headers.
? Diagnosis & Resolution Workflow
Step 0: Non-Interactive Context Discovery & Dry-Run Fallback
-
Parameter Extraction: Extract required context (
project_id,cluster_name,cluster_location,hpa_name,workload_name,workload_namespace) non-interactively from the user prompt, activeSETTINGS.md, or environment defaults:- Default
workload_namespacetodefaultif omitted. - Infer missing cluster parameters from the active environment (
kubectl config current-contextorgcloud config get-value project).
- Default
-
Cluster Credentials & Fallback Mode:
- Attempt credential fetch:
gcloud container clusters get-credentials {cluster_name} --location {cluster_location} --project {project_id}. - Fallback / Dry-Run Mode: If the cluster is unreachable,
non-existent, or live command execution fails (such as in sandboxed
evaluations, dry-run mode, or offline analysis):
- Limit retry attempts to avoid resource exhaustion and context overflow.
- Immediately present the exact
kubectl/gclouddiagnostic commands for the human operator to run. - Synthesize the root-cause analysis and output the proposed GitOps correction based on the reported symptoms.
- Attempt credential fetch:
Step 1: Inspect the HPA and Classify the Symptom
Start every investigation with kubectl describe hpa, then route to the matching
branch. The three key sections are Metrics (an <unknown> value means the
HPA hasn't fetched the metric or the pipeline is broken), Conditions
(AbleToScale, ScalingActive, ScalingLimited — a False status marks a
failure), and Events (specific reasons such as FailedGetScale or
FailedGetResourceMetric).
Diagnostic Commands:
kubectl describe hpa {hpa_name} -n {workload_namespace}
kubectl get hpa {hpa_name} -n {workload_namespace} -o yaml
For historical events, query Cloud Logging (the HPA events survive after the live
Events list rolls over):
resource.type="k8s_cluster"
resource.labels.cluster_name="{cluster_name}"
resource.labels.location="{cluster_location}"
logName="projects/{project_id}/logs/events"
jsonPayload.involvedObject.kind="HorizontalPodAutoscaler"
Route by signal:
FailedGetScale,FailedComputeMetricsReplicas,Error 400 ... label is not allowed, or fluctuating replicas from competing HPAs → Branch A (Configuration Errors).FailedGetResourceMetric,unable to fetch pod metrics, ormultiple services selecting the same target→ Branch B (Workload & Service Errors).<unknown>custom/external metric,FailedGetExternalMetric/FailedGetCustomMetric, orno known available metric versions found→ Branch C (Metrics API & Data Availability).- Conditions all
True/ no errors but the workload won't scale up or down → Branch D (Healthy but Unexpected Scaling). - Workload configured with
minReplicas: 0won't scale to or from zero → Branch E (Scale To / From Zero). - Correct HPA but slow reaction on a cluster with many HPA objects → Branch F (Slow Recalculation on Large Clusters).
Step 2: Resolution — Route to the Matching Branch
Based on the signal you classified in Step 1, jump to one of the mutually-exclusive branches below (A–F). These are alternatives — you do not run them in sequence. After applying the branch's fix, go to Step 3 to present it as a reviewable GitOps change.
Branch A: HorizontalPodAutoscaler Configuration Errors
-
FailedGetScale—unable to get the target's current scale: ... "TARGET" not found: thescaleTargetRefdoesn't resolve to an existing scalable workload.- Verify the
scaleTargetRefname,kind, andapiVersionexactly match the target workload's metadata. - Confirm the target workload exists in the same namespace as the HPA
(a missing
-nputs objects indefault, causing a mismatch). - The target must be a scalable kind (Deployment, StatefulSet, ReplicaSet) — you cannot autoscale a DaemonSet.
- Verify the
-
FailedComputeMetricsReplicas—invalid metrics (1 invalid out of 1): the metrictypeandtargetdon't match.- If
type: Utilization, the target must beaverageUtilization. - If
type: AverageValue, the target must beaverageValue.
- If
-
unable to fetch metrics from external metrics API: googleapi: Error 400: Metric label: 'LABEL' is not allowed: an invalid key inmetric.selector.matchLabels.- Remove or correct the disallowed label; find valid filterable labels in the Cloud Monitoring metric documentation.
-
Replica count fluctuates / contradictory
SuccessfulRescaleevents from different HPAs: more than one HPA targets the same workload viaspec.scaleTargetRef, and they compete. There is no dedicated condition for this — confirm withkubectl get hpa -n {workload_namespace} -o yamland look for duplicatescaleTargetRefvalues.- Consolidate all metrics into one HPA object (it takes the highest of
its
spec.metrics) and delete the duplicates.
- Consolidate all metrics into one HPA object (it takes the highest of
its
Branch B: Workload & Service Errors
-
ScalingActive: False, reasonFailedGetResourceMetric, messageunable to compute the replica count(or a persistentunable to fetch pod metrics): the HPA computes utilization as a percentage of the container resource request, but at least one container in the Pod is missing aresources.requestsentry for the scaled resource (cpuormemory).- Add
resources.requestsfor the scaled resource to every container in the Pod spec (including sidecars). A briefunable to fetch pod metricsright after the metrics server starts is normal and self-heals.
- Add
-
multiple services selecting the same target of HPA_NAME: SERVICE: traffic-based autoscaling requires a one-to-one Service↔workload relationship, but more than one Service's selector matches the workload's Pods.- Make the intended Service's selector unique (add a distinct label to the workload and to that one Service), or tighten the other Services' selectors so they no longer match the workload's Pods.
Branch C: Metrics API & Data Availability (Custom / External Metrics)
The custom/external pipeline is: HPA controller → Kubernetes metrics API server
→ metrics adapter (for example custom-metrics-stackdriver-adapter) → metric
source (Cloud Monitoring / Prometheus). Symptoms are <unknown> metric values or
FailedGetExternalMetric / FailedGetCustomMetric events.
-
Is the adapter registered and available?
kubectl get apiservice | grep -E 'NAME|metrics.k8s.io'Expect
v1beta1.custom.metrics.k8s.ioand/orv1beta1.external.metrics.k8s.iowithAVAILABLE: True. IfFalse/missing, the adapter is crashed or misconfigured — inspect its Pod logs in thecustom-metricsorkube-systemnamespace for permission, connectivity, or "metric not found" errors. -
Query the metrics API directly (bypasses the HPA to test the whole pipeline;
jqoptional):kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/{workload_namespace}/{metric_name}" | jq . kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/namespaces/{workload_namespace}/pods/*/{metric_name}" | jq . -
Interpret the result:
- Valid JSON with a value → the pipeline works; the fault is in the HPA
manifest (metric-name typo or wrong
matchLabels). Error from server (Service Unavailable)→ network isolation is blocking the control plane from reaching the adapter. Add the adapter'stargetPortto the control-plane firewall rule (in addition to the existingtcp:443andtcp:10250). Identify the rule withgcloud compute firewall-rules list --filter="name~gke-{cluster_name}-[0-9a-z]*-master", and also confirm no NetworkPolicy blocks ingress to the adapter Pods.- Empty list
[]→ the adapter runs but can't retrieve the metric. Inspect the adapter Pod logs, and confirm in Metrics Explorer that the metric actually exists in the source with the expected name and labels.
- Valid JSON with a value → the pipeline works; the fault is in the HPA
manifest (metric-name typo or wrong
-
unable to fetch metrics from custom metrics API: no known available metric versions found: a communication breakdown (control plane briefly unavailable during an upgrade/repair, or the adapter Pods are unhealthy or not registered) — not a problem at the metric source. Check control-plane health/notifications, confirm the adapter Pods areRunningwith no restarts (kubectl get pods -n custom-metrics,kube-system -o wide), and re-verify the APIServices areAVAILABLE: True. Often transient. -
googleapi: Error 400: The supplied filter ... will not return any time series: the query is valid but no data matched (different from a value of0) — the application wasn't writing the metric during the window. Verify the metric name/labels match what the app emits, confirm the app had permission and was active, and check the app logs for metric-emission errors.
Branch D: Healthy but Unexpected Scaling Behavior
The HPA's conditions are True and it shows no errors, but scaling doesn't
happen as expected.
-
Won't scale up — check, in order:
- Replica limits:
currentReplicasis already atminReplicas/maxReplicas(see theScalingLimitedcondition); adjust the bounds. - Tolerance window: Kubernetes ignores changes while the
current/target ratio stays within
0.9–1.1(default 10% tolerance). Example: target 85% CPU, current 93% → ratio ≈ 1.094 < 1.1, so no scale-up. Wait for the metric to move outside the band, or configure a different tolerance. - Unready Pods:
Pending/not-ReadyPods are excluded from the calculation — resolve the underlying scheduling/probe issue. - Sync delay: a 15–30s delay between threshold crossing and action is normal.
- Replica limits:
-
Won't scale down — check, in order:
- Multiple metrics: the HPA uses the metric demanding the most replicas, so it won't scale down unless all metrics agree.
- Unavailable metric halts scale-down: if any metric goes
<unknown>the HPA conservatively refuses to scale down. Common with rate-based custom metrics that stop reporting at zero traffic. Prefer gauge metrics (for examplenum_undelivered_messages) or make the source publish0during inactivity rather than sending no data. - Scale-down stabilization window: the default
behavior.scaleDown.stabilizationWindowSecondsis 300s (5 min). Lower it if scale-down must be faster.
Branch E: Scale To / From Zero (GKE 1.37+)
Scaling a workload to and from zero replicas with HPA (minReplicas: 0) is
supported on GKE 1.37 or later.
-
Won't scale to zero:
minReplicas: 0must be set.- The HPA cannot scale to zero using only
Resource(CPU/memory) metrics — configure at least oneExternalorObjectmetric. - With multiple metrics, all must evaluate to zero.
- GKE waits the 5-minute scale-down stabilization window at zero demand before going from 1→0.
- Any metric showing
<unknown>pauses scale-down (see Branch D).
-
Won't scale up from zero: run
kubectl describe hpa {hpa_name}and check:- Metrics: the value must be
> 0and not<unknown>; if missing, confirm the external source (for example Pub/Sub) is publishing and Cloud Monitoring is receiving. - Conditions: a healthy idle state shows
AbleToScale: True,ScalingActive: True,ScaledToZero: True. IfScalingActive: Falsewith reasonScalingDisabledExternalScaleToZeroorScalingDisabledReplicaCountZero, the workload was manually scaled to zero (for examplekubectl scale), which pauses autoscaling. Resume it by scaling the Deployment back to--replicas=1. - Cold-start latency from node provisioning can add delay; Capacity Buffers keep standby capacity ready.
- Metrics: the value must be
Branch F: Slow HPA Recalculation on Large Clusters
If HPAs are correct but react slowly, the cluster may exceed the HPA object count the standard controller keeps within a 15-second recalculation period.
- Standard controller: within 15s for up to 300 HPA objects (GKE 1.22+).
- Performance HPA profile: within 15s for up to 1,000 HPA objects (GKE 1.31+) or 5,000 HPA objects (GKE 1.33+, where it is enabled by default on eligible clusters).
Enable it on an eligible cluster (this is a cluster mutation — present it for the operator to run, don't execute it):
gcloud container clusters update {cluster_name} \
--location {cluster_location} --project {project_id} \
--hpa-profile=performance
Scaling on many metrics per HPA and slow (>~50 ms) custom-metric adapters also lengthen the recalculation period. For visibility into scaling decisions, enable HPA event logging and review the structured HPA decision logs.
Step 3: Propose the GitOps Correction
Enforce the read-only diagnostics boundary: do not apply live mutations. This
includes cluster/manifest changes (kubectl edit, kubectl patch, kubectl apply, kubectl scale, kubectl delete) and Google Cloud / gcloud changes
(cluster updates such as --hpa-profile, and gcloud compute firewall-rules
updates). Instead, present the corrected HorizontalPodAutoscaler, PodSpec
(resources.requests), Service selector, workload autoscaling
configuration, or the gcloud command as a reviewable patch/command to be
applied through the user's GitOps pipeline (for example Config Sync, Argo CD, or
Flux) or by an authorized operator.
References
- Troubleshoot horizontal Pod autoscaling in GKE
- Horizontal Pod autoscaling (concepts, Performance HPA profile & limits)
- Configure horizontal Pod autoscaling (hpa-profile)
- View horizontal Pod autoscaling events
- Scale to and from zero using HPA
- Kubernetes HorizontalPodAutoscaler (tolerance & scaling policies)
04 同仓库更多 Skills
cloud-operator-share-context
Shares Google Cloud operating context the user or their team already have — environments, projects, services and regions, product preferences, best practices, architecture guidance, runbooks — found in agent instruction files, local memory, skills and workflows, and the repository's GCP docs, with the operator agent's memory after the user reviews the list. Use when the user runs this skill, accepts the cloud-operator or cloud-operator-setup skill's offer to share their existing Google Cloud context, or asks to share, import or save that context or a GCP fact for the operator agent. Don't use for ordinary GCP requests, which go to the cloud-operator skill.
cloud-operator-setup
Sets up the operator agent in a Google Cloud project via the autocloud MCP server: picks the operator project, creates or checks the user's operator agent, saves the project, and offers to share the user's existing Google Cloud operating context with the operator agent's memory. Use when the user runs this skill, asks to set up the operator or create their operator agent, or chooses setup when the cloud-operator skill asks. Don't use for ordinary GCP requests or installing gcloud.
developer-device-platform-device-run
Runs automated, non-interactive jobs on remote Android devices with Developer Device Platform (DDP) Device Run using `gcloud beta device-run sessions`: native Android executables or shell scripts (for example CLI tools, custom runners, test harnesses or benchmarks) and Android instrumentation tests, on one or many devices, then waits for completion and collects per-device outputs and logs. Use when running a binary or test suite on remote devices without an interactive connection. Don't use it for interactive device reservations, adb tunnels or screen streaming (use developer-device-platform-basics), or for local devices.
compute-vm-creation
Guides the planning, configuration, and provisioning of standalone Google Compute Engine virtual machines (VMs) and bare metal (-metal) instances using gcloud CLI commands or direct MCP tool execution. Use ONLY when the user wants to create, configure, or provision a new standalone Compute Engine VM or bare metal instance from conversational intents (hardware sizing, region selection, OS image, networking, security defaults). DO NOT read or use for Google Kubernetes Engine (GKE) Autopilot or Standard clusters, Kubernetes node pools or Pods, container orchestration, managing existing VMs, Managed Instance Groups (MIGs), or Instance Templates.
agent-platform-autorater-customization
Customizes an autorater (evaluation metric) for an AI agent so its grades match the user's own judgment, starting from the agent's real trajectories. Use when a user wants a metric tailored to their agent, wants to turn failing trajectories into rubrics, says an existing autorater grades their agent wrong, or wants an autorater to agree with human labels (autorater hillclimbing, judge calibration). Don't use for quick evals with built-in metrics or for improving the agent itself (use agent-platform-eval-flywheel).
iap-agent-platform-troubleshooting
Diagnoses Identity-Aware Proxy (IAP) denials of outbound requests from Gemini Enterprise Agent Platform agents that run on Agent Runtime and send traffic through Agent Gateway. Use when an agent request fails with "Egress request is not authorized", when Cloud Audit Logs show an IAP egressViaIAP decision with granted false, when IAP audit entries are missing while debugging agent egress, or when Access policies, IAP allow policies, policy bindings, or Agent Registry entries might block agent egress. Don't use for Gemini model IAM permission errors (such as aiplatform.endpoints.predict), Agent Platform API errors, or Agent Runtime deployment or 500 errors (use agent-platform-troubleshooting instead). Don't use for setting up, creating, or connecting an Agent Gateway, or for IAP web apps, IAP TCP forwarding, or SSH.