gke-observability
google/skills · 8.1k installs · 21.7K stars
Skill This reference covers monitoring, logging, and metrics configuration for GKE. The golden path enables comprehensive observability including control-plane metrics.
Marked Command Execution · External Downloads
Install
The repo has no one-line install. Follow its README.
Files
GKE Observability
This reference covers monitoring, logging, and metrics configuration for GKE. The golden path enables comprehensive observability including control-plane metrics.
MCP Tools:
get_cluster,list_k8s_events,get_k8s_logs,get_k8s_cluster_info,describe_k8s_resource. CLI-only:gcloud container clusters update --monitoring=...,gcloud logging read
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-observability)"
and append agent-skills/1.0 (skill:gke-observability) to User-Agent headers.
Golden Path Observability Defaults
| Setting | Golden Path Value | Notes |
|---|---|---|
loggingConfig components |
SYSTEM_COMPONENTS, WORKLOADS | Full workload logging |
monitoringConfig components |
SYSTEM_COMPONENTS, STORAGE, POD, DEPLOYMENT, STATEFULSET, DAEMONSET, HPA, JOBSET, CADVISOR, KUBELET, DCGM, APISERVER, SCHEDULER, CONTROLLER_MANAGER | Full suite including control-plane |
managedPrometheusConfig.enabled |
true |
Google-managed Prometheus |
advancedDatapathObservabilityConfig.enableMetrics |
true |
Dataplane V2 flow metrics |
loggingService |
logging.googleapis.com/kubernetes |
Cloud Logging |
monitoringService |
monitoring.googleapis.com/kubernetes |
Cloud Monitoring |
Control-Plane Metrics (Golden Path Addition)
The golden path adds three control-plane monitoring components not present in default clusters:
| Component | What It Monitors |
|---|---|
APISERVER |
API server request latency, error rates, admission webhook performance |
SCHEDULER |
Scheduling latency, pending pods, scheduling failures |
CONTROLLER_MANAGER |
Controller work queue depth, reconciliation latency |
These are critical for diagnosing cluster-level issues (slow API responses, scheduling delays, stuck controllers).
Control-plane (KCP) VM CPU and RAM/memory usage are not publicly exposed: GKE manages control-plane VMs internally and exposes no KCP VM CPU or RAM/memory usage metrics in Cloud Monitoring (
kubernetes.io/cluster/*,kubernetes.io/master/*, or worker-node-onlykubernetes.io/node/*/container_*) or Managed Service for Prometheus. Instead of KCP VM CPU, monitorkubernetes.io/cluster/kcp_healthchecks,apiserver_request_duration_seconds, and APF concurrency saturation (apiserver_flowcontrol_priority_level_seat_utilizationandapiserver_current_inflight_requests). Instead of KCP VM RAM/memory, monitorapiserver_resource_size_estimate_bytes,apiserver_storage_size_bytes(kubernetes.io/cluster/storage/used_bytesandkubernetes.io/cluster/storage/limit_bytes), andkubernetes.io/cluster/kcp_healthchecks.
When recommending any control-plane metric below, always state that it is a
Managed Service for Prometheus (GMP) metric that requires explicit enabling
(--monitoring=SYSTEM,API_SERVER,... and --enable-managed-prometheus) and
link to
https://docs.cloud.google.com/kubernetes-engine/docs/how-to/control-plane-metrics:
- API storage utilization by resource
(
apiserver_resource_size_estimate_bytes): Useapiserver_resource_size_estimate_bytes(orkubernetes.io/master/apiserver/resource_size_estimate_bytes, grouped bygroupandresource) alongsideapiserver_storage_objects(grouped bygroupandresource) to identify which Kubernetes resource types or CRDs consume the most API server storage bytes in etcd, complementing total database size (apiserver_storage_size_bytes) and real-time cluster storage quota metrics (kubernetes.io/cluster/storage/used_bytesandkubernetes.io/cluster/storage/limit_bytesin Cloud Monitoring).- Quota exhaustion (
etcdserver: mvcc: database space exceeded), scalability limits, and CRD bloat: Configure a Cloud Monitoring alert onkubernetes.io/cluster/storage/used_bytes / kubernetes.io/cluster/storage/limit_bytes(orapiserver_storage_size_bytes) before storage approaches capacity, and compare per-resource byte footprints against GKE scalability limits (https://cloud.google.com/kubernetes-engine/docs/concepts/planning-large-clusters: keep total Pod or ReplicaSet state below ~800 MiB per resource type, keep individual ConfigMaps/Secrets below 1 MiB vs. the 1.5 MiB etcd hard limit, and stay below ~30,000 Secrets/ConfigMaps). When storage quota is exhausted and object creations, updates, or controller Lease renewals fail (while some earlier GKE versions blocked all edits upon hitting storage quota,kubectl deletenow remains permitted), prune bloated resources (retained ReplicaSets viarevisionHistoryLimit, finishedbatch/v1Jobs and runaway CronJob pods withconcurrencyPolicy: Allow, accumulated Kyvernoadmissionreports, oversized ConfigMaps/Secrets, or custom resources stuck on missing finalizers) in small paced batches, and set.spec.ttlSecondsAfterFinishedon Jobs plussuccessfulJobsHistoryLimitandfailedJobsHistoryLimiton CronJobs. - Excessive
VolumeSnapshotobjects hangingLIST: When newVolumeSnapshotobjects take tens of minutes to become ready or deleted snapshots stay stuck inTerminating, checkapiserver_storage_objectsandapiserver_resource_size_estimate_bytes(orkube-apiserverslowLISTtrace logs) forvolumesnapshotsandvolumesnapshotcontentsto see if excessive object count or byte size is causingsnapshot-controllerLISTcalls to time out; prune oldVolumeSnapshotandVolumeSnapshotContentobjects and enforce a retention policy keeping the total count well below 50,000.
- Quota exhaustion (
- Admission webhook latency, timeouts, and control-plane recommendations
(
apiserver_admission_webhook_admission_duration_seconds): When API calls or pod creations time out (context deadline exceeded) or fail and mutating or validating admission webhooks are suspected, query the opt-in GMP metricapiserver_admission_webhook_admission_duration_seconds(grouped byname,type,operation, andrejected) alongsidekube-apiserverslow-requestTrace[logs, GKE Control Plane / Webhook Insights (Verify webhook with unavailable endpoints), andkubernetes.io/cluster/kcp_healthchecks(to verify whether the GKE control plane itself is healthy before requesting a control-plane upsize). Tune the webhook timeout (timeoutSeconds), fix or scale the backing webhook service pods, or adjustfailurePolicyso slow image inspection or unavailable webhook backends do not block pod creation.- Webhook rules, system namespace exclusions, CNI initialization, and
upgrade deadlocks: Inspect
ValidatingWebhookConfigurationandMutatingWebhookConfigurationrules,timeoutSeconds, andfailurePolicy. Always excludekube-systemandkube-node-leasevianamespaceSelectoron third-party webhooks (such as Kyverno, Datadog, Vault, OpenTelemetry, or Gatekeeper'sadmission.gatekeeper.sh/ignorelabel) and removecoordination.k8s.ioleases(coordination.k8s.io/leases) from webhook rules so crashed or slow webhooks never block controller Lease renewals orkube-systemCNI pods (netd,anetd, leaving new nodes stuckNotReadywithCNI plugin not initialized). If control-plane upgrades fail and roll back or Cluster Autoscaler stops initializing after an upgrade, check Cloud Audit Logs or webhook metrics/logs during the upgrade window for denied or timed-out requests fromsystem:apiserver(onrbac.authorization.k8s.io/clusterrolebindings) orsystem:addon-manager(on systemcustomresourcedefinitionssuch ascapacitybuffers.autoscaling.x-k8s.io), and exemptrbac.authorization.k8s.iobootstrap bindings and GKE system CRDs (*.gke.io,autoscaling.x-k8s.io) from webhook rules or setfailurePolicy: Ignore(or remove the broken webhook). - Broken
APIService, bloated API discovery, CRD conversion webhooks, unavailable endpoints, and OOMKilled webhook pods: Runkubectl get apiservices(andkubectl --v=6alongsideapiserver_response_sizesandapiserver_request_duration_seconds) to spot unavailableAPIServicebackends or multi-megabyte discovery responses from aggregated APIs such ascustom.metrics.k8s.ioorexternal.metrics.k8s.io(disable or filter unbounded custom metrics exporters such as Airflow or Prometheus adapters exporting thousands of metric series into API discovery). Inspect CRD conversion webhook targets (spec.conversion.webhook) and verify that webhookEndpointSliceaddresses match running pod IPs. When a webhook has unavailable endpoints, inspectMutatingWebhookConfigurationandValidatingWebhookConfigurationservice references, check backing pod health and OOM kills (jsonPayload.reason="OOMKilling",kubectl describe pod, andkubectl logs <pod> --previous), increase memory limits on OOMKilled webhook controller pods (such as Gatekeeper or Kubeflowcache-server), fix the backing deployment, or scope webhook rules andfailurePolicyso unavailable endpoints do not block unrelated API operations. - Control-plane recommendations: Strongly warn users against ignoring
GKE control-plane recommendations about optimizing admission webhooks or
CRDs with an invalid
caBundlebecause unoptimized webhooks and invalid CRDcaBundleconfigurations can overload or destabilize the GKE control plane, and always link to https://docs.cloud.google.com/kubernetes-engine/docs/how-to/optimize-webhooks.md.txt and https://docs.cloud.google.com/kubernetes-engine/docs/how-to/crd-with-invalid-caBundle.md.txt.
- Webhook rules, system namespace exclusions, CNI initialization, and
upgrade deadlocks: Inspect
- Watch activity and watch storms (
apiserver_longrunning_requests,apiserver_watch_events_total,apiserver_watch_events_sizes): When a misconfigured agent or DaemonSet is suspected of causing a watch storm or repeatedly re-establishing broken watches, check the GMP metricsapiserver_longrunning_requests(filtered byverb="WATCH", grouped bygroup,resource,scope) for active concurrent watchers,apiserver_watch_events_total(grouped bygroup,kind,version) for watch event volume and rate, andapiserver_watch_events_sizesfor watch event payload sizes. - Pod and object churn, controller-manager workqueue backlog, and scheduler
lag (
workqueue_depth,workqueue_queue_duration_seconds,job_controller_*,scheduler_pending_pods,scheduler_schedule_attempts_total,scheduler_scheduling_attempt_duration_seconds, and mutatingapiserver_request_total): When batch job bursts (thousands of concurrent Jobs) or controller loops leave newly created pods stuck inPending, delay pod creation by 10–20 minutes, makekubectlcommands sluggish, or cause controller reconciliations to lag, enableSCHEDULERandCONTROLLER_MANAGERcontrol-plane metrics and always query all three ofworkqueue_depth,workqueue_queue_duration_seconds, andjob_controller_*metrics (such asjob_controller_job_sync_duration_seconds) onkube-controller-manageralongsidescheduler_pending_pods,scheduler_schedule_attempts_total, andscheduler_scheduling_attempt_duration_secondsonkube-scheduler(and mutatingapiserver_request_totalCREATE,DELETE,PATCH,UPDATE); mitigate by pacing job creation or batching workloads.
Enabling Full Monitoring
Say this whenever you hand over a --monitoring command:
- Control-plane metrics and logs are NOT enabled by default. State this
outright in your answer — do not leave it implied by the fact that you are
supplying an enable command.
API_SERVER,SCHEDULER, andCONTROLLER_MANAGERare off on every new cluster and collect nothing until explicitly turned on, and the same is true ofDCGM,CADVISOR,KUBELET, and kube-state (POD,DEPLOYMENT,STATEFULSET,DAEMONSET,HPA,STORAGE,JOBSET).SYSTEMis the only package on by default. A user asking "why are there no API server, scheduler, or controller-manager metrics or logs" has almost always simply never enabled them. - The flag replaces, it does not append. The set supplied to
--monitoring(and--logging) overrides the previous setting entirely, so omitting a component silently turns it off. Always pass the full desired list, and always includeSYSTEM— it cannot be disabled while monitoring is on, and never on Autopilot. - These metrics bill per sample ingested via Managed Service for Prometheus. Enabling the full suite on a large cluster is a real cost increase; mention it rather than presenting the list as free.
- Always verify that Cloud Logging and Cloud Monitoring are enabled on the
cluster and check IAM permissions (
PermissionDenied). Always advise the user to verify that Cloud Logging and Cloud Monitoring are enabled on the cluster (gcloud container clusters describe <CLUSTER_NAME> --region <REGION> --format="yaml(loggingConfig,monitoringConfig)"and ensuringlogging.googleapis.comandmonitoring.googleapis.comare enabled), and that the node service account and GKE service agent haveroles/monitoring.metricWriterandroles/container.defaultNodeServiceAgentwhen metrics fail withPermissionDenied.
The gcloud flag and the API field use different spellings for the same components. Do not copy names between them:
Component gcloud --monitoring=monitoringConfigAPI enumSystem SYSTEMSYSTEM_COMPONENTSAPI server API_SERVERAPISERVERController mgr CONTROLLER_MANAGERCONTROLLER_MANAGERThe remaining components share a spelling. Using an API enum in the CLI flag (or the reverse) fails the command — this is a common and confusing error.
# Enable golden path monitoring and control-plane logging suite
gcloud container clusters update <CLUSTER_NAME> --region <REGION> \
--monitoring=SYSTEM,API_SERVER,SCHEDULER,CONTROLLER_MANAGER,STORAGE,POD,DEPLOYMENT,STATEFULSET,DAEMONSET,HPA,JOBSET,CADVISOR,KUBELET,DCGM \
--logging=SYSTEM,WORKLOAD,API_SERVER,SCHEDULER,CONTROLLER_MANAGER \
--quiet
# Enable Managed Prometheus
gcloud container clusters update <CLUSTER_NAME> --region <REGION> \
--enable-managed-prometheus \
--quiet
# Enable Dataplane V2 observability metrics
gcloud container clusters update <CLUSTER_NAME> --region <REGION> \
--enable-dataplane-v2-flow-observability \
--quiet
Managed Prometheus
Golden path enables Google Managed Prometheus for metrics collection and querying.
Querying metrics:
- Use Cloud Monitoring Metrics Explorer in the console
- Use PromQL via the Prometheus UI or API
- Grafana dashboards via Managed Grafana
Key GKE metrics:
| Metric | Source | Use |
|---|---|---|
container_cpu_usage_seconds_total |
cAdvisor | Pod CPU usage |
container_memory_working_set_bytes |
cAdvisor | Pod memory usage |
kube_pod_status_phase |
kube-state-metrics | Pod lifecycle |
apiserver_request_duration_seconds |
API Server | Control plane latency |
scheduler_scheduling_attempt_duration_seconds |
Scheduler | Scheduling performance |
kubernetes.io/node/cpu/core_usage_time |
Cloud Monitoring | Node CPU |
DCGM_FI_DEV_GPU_UTIL |
DCGM | GPU utilization |
Live Resource Usage (kubectl-only)
No MCP or gcloud equivalent exists for live resource usage. Use kubectl top:
kubectl top pods --all-namespaces --sort-by=cpu
kubectl top nodes
kubectl top pods --containers -n <NAMESPACE> # per-container breakdown
Cloud Logging (gcloud-only)
Querying cluster logs (no MCP equivalent — use gcloud logging read):
# System component logs
gcloud logging read \
'resource.type="k8s_cluster" AND resource.labels.cluster_name="<CLUSTER_NAME>"' \
--project <PROJECT_ID> --limit 50 \
--quiet
# Workload logs for a specific namespace
gcloud logging read \
'resource.type="k8s_container" AND resource.labels.cluster_name="<CLUSTER_NAME>" AND resource.labels.namespace_name="<NAMESPACE>"' \
--project <PROJECT_ID> --limit 50 \
--quiet
# Audit logs (who did what)
gcloud logging read \
'resource.type="k8s_cluster" AND logName:"cloudaudit.googleapis.com"' \
--project <PROJECT_ID> --limit 50 \
--quiet
- Hot-object write contention,
409 Conflictstorms, and leader-electionRenewDeadlinetimeouts: When frequent409 Conflicterrors and highPATCH/PUTlatencies suggest runaway controllers are fighting over or excessively patching a single Kubernetes object (such as a largeConfigMap,CustomResourceDefinition, orLease), query GKE Cloud Audit Logs (cloudaudit.googleapis.com/activity) grouped byprotoPayload.resourceName,protoPayload.methodName(updateorpatch), andprotoPayload.requestMetadata.callerSuppliedUserAgent(orprotoPayload.authenticationInfo.principalEmail) and inspectkube-apiserverGuaranteedUpdatetrace logs to pinpoint the hot object and responsible agent; mitigate by reducing the operator's checkpoint or sync frequency (such as increasingrefreshInterval) and lowering client QPS. If third-party operators repeatedly lose Lease leadership withcontext deadline exceededafter 5 seconds despite higher general client timeouts, note thatclient-go'sleaderelectionpackage sets the per-request HTTP timeout on LeasePUTrenewals toRenewDeadline / 2(so the defaultRenewDeadline: 10senforces?timeout=5s, visible onrequestURIin Cloud Audit Logs andkube-apiservertrace logs); increase the operator's leader-election flags (such as--leader-elect-lease-duration=60sand--leader-elect-renew-deadline=40s). - Excessive
pods/execand Konnectivity (No agent available/ firewall /ip-masq-agent): Whenwarden-validating.common-webhooks.networking.gke.ioadmission timeouts (10s) or500 error dialing backend: dial timeout, backstoperrors occur onkubectl exec, query Cloud Audit Logs forio.k8s.core.v1.pods.exec.get(connect) request volume and correlate withapiserver_admission_webhook_admission_duration_secondsforwarden-validating(highpods/execvolume evaluates against admission webhooks and Konnectivity tunnels); replacekubectl exec-based metrics scraping and health checks with Kubelet/metrics/cadvisoror Cloud Monitoring container metrics (k8s_container) and direct pod-to-pod HTTP/gRPC endpoints. If webhook calls orkubectl exec/logsfail withNo agent availableorcontext deadline exceeded, checkkube-apiserverlogs (resource.type="k8s_control_plane_component") forNo agent availableor dial failures, inspectkonnectivity-agentpods inkube-system(kubectl get pods -n kube-system -l k8s-app=konnectivity-agent), verify VPC firewall rules between the control-plane CIDR and node/pod CIDRs (ports10250,8132, and webhook ports), and check theip-masq-agentConfigMap so pod-to-API-server and API-server-to-webhook traffic is not masqueraded or blocked. - Disabled Cloud KMS keys breaking control-plane encryption
(
kms-provider-0/failed to get dek primitive): Inspectgcloud container clusters describe(databaseEncryptionconfiguration and error status) and query Cloud Audit Logs forcloudkms.googleapis.com(DisableCryptoKeyVersion,DestroyCryptoKeyVersion, orPermissionDeniedonEncrypt/Decrypt). Recover by re-enabling the disabled Cloud KMSCryptoKeyVersion, ensuring the GKE service agent has theroles/cloudkms.cryptoKeyEncrypterDecrypterIAM role, and following https://docs.cloud.google.com/kubernetes-engine/docs/how-to/encrypting-secrets#reencrypt-secrets to re-encrypt existing Secrets after key rotation or recovery. - In-cluster GCP IAM OAuth tokens saturating the GKE IAM webhook authorizer
(
Failed to make webhook authorizer request): When high-QPS in-cluster clients (Helm, operators) authenticate with GCP IAM OAuth Bearer tokens without matching Kubernetes RBAC bindings,kube-apiservermust invoke the external GKE IAM webhook authorizer on every request, which can throttle or time out under load (Failed to make webhook authorizer request: the server is currently unable to handle the request). Inspect Cloud Audit Logs (protoPayload.authenticationInfoandprotoPayload.authorizationInfo) and migrate in-cluster workloads to native KubernetesServiceAccounttokens bound via Kubernetes RBAC (RoleBinding/ClusterRoleBinding) so authorization is evaluated locally in memory. - End-to-end pod startup lifecycle, mass eviction, and Autopilot
preemption: To determine whether a slow-starting pod was delayed during
controller creation, scheduling,
kubeletpickup, or container startup, reconstruct its timeline in Cloud Logging by correlating Kubernetes Events (resource.type="k8s_pod"ork8s_event) with Cloud Audit Logs (cloudaudit.googleapis.com/activity), optional control-plane component logs (kube-scheduler,kube-controller-manager, andkube-apiserverunderresource.type="k8s_control_plane_component"), and nodekubeletlogs (resource.type="k8s_node").tolerationSeconds: 0mass pod eviction: If pods are simultaneously evicted during a brief control-plane hiccup when nodes briefly enterNodeStatusUnknown, inspect workload Pod or Deployment specs (kubectl get deploy -o yaml) for customtolerationsonnode.kubernetes.io/unreachable(NoExecute) andnode.kubernetes.io/not-ready(NoExecute) that settolerationSeconds: 0(which overrides Kubernetes's default 300-second eviction grace period), and remove thetolerationSeconds: 0override.- Autopilot single-node bin-packing and system-addon preemption: If
all replicas of a Deployment pack onto a single node at its
maxPodslimit (32/32on Autopilot), surgingsystem-cluster-criticaladdons (priority2000000000) during a control-plane upgrade trigger scheduler preemption, which bypassesPodDisruptionBudgetwhen no other capacity is immediately available; configuretopologySpreadConstraintsorpodAntiAffinityacross nodes/zones so replicas never co-locate on a single node, and assign an appropriatePriorityClass.
Diagnostic Settings
For security monitoring and troubleshooting, enable control-plane audit logs:
# View current logging config
gcloud container clusters describe <CLUSTER_NAME> --region <REGION> \
--format="yaml(loggingConfig)" \
--quiet
Control-Plane Component Logs & Slow Request Traces
kube-apiserver component logs (API_SERVER) are an optional feature that is
not enabled by default and must be explicitly turned on
(--logging=SYSTEM,WORKLOADS,API_SERVER); always mention this and link to
https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs#control_plane_logs
when recommending apiserver log analysis.
To diagnose which specific kube-apiserver requests were slow and why:
- Search for
traceorTraceentries: Queryapiservercomponent logs (resource.type="k8s_control_plane_component" AND resource.labels.component_name="apiserver") fortraceorTrace(for example,textPayload:"Trace["). - How to interpret trace logs:
kube-apiserveruses the upstreamk8s.io/utils/tracepackage (trace.go) to log requests that exceed a latency threshold (typically 500ms). Each trace header records the operation ("List","Get","Create","Patch"),url,user-agent,audit-id,clientIP, start timestamp, andtotal time. Below the header, nested sub-traces appear in brackets[...]and sequential steps exceeding the step threshold appear as---"<StepName>" <duration>ms. - Example trace logs for typical problems:
- Slow etcd / storage read or write (
cacher.GetList,List(recursive=true) etcd3, orGuaranteedUpdate etcd3withinitial value restored/Txn call completeddominatestotal time):I1015 11:36:56.835120 10 trace.go:236] Trace[123456789]: "List" url:/api/v1/pods,user-agent:my-controller/v1.0.0,audit-id:11111111-2222-3333-4444-555555555555,client:10.0.0.1 (15-Oct-2026 11:36:49.460) (total time: 7374ms): Trace[123456789]: ["List(recursive=true) etcd3" 6890ms (11:36:49.461)] Trace[123456789]: ---"Objects listed" 6891ms (11:36:56.352) Trace[123456789]: ---"SerializeObject" 480ms (11:36:56.832) - Slow client / response streaming bottleneck (
"Objects listed"is fast, but"SerializeObject"and---"Write call succeeded"or---"Write call failed"dominatetotal timebecause a slow or bandwidth-constrained client takes seconds to read a large response payload):I1015 11:40:12.104512 10 trace.go:236] Trace[987654321]: "List" url:/api/v1/pods,user-agent:slow-watcher/v0.1,audit-id:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee,client:10.0.0.2 (15-Oct-2026 11:40:01.002) (total time: 11102ms): Trace[987654321]: ---"Objects listed" 45ms (11:40:01.047) Trace[987654321]: ["SerializeObject" 11055ms (11:40:01.047)] Trace[987654321]: ---"Write call succeeded" 11054ms (11:40:12.101)
- Slow etcd / storage read or write (
- Upstream documentation & future evolution (always cite both): Always
link to https://github.com/kubernetes/utils/blob/master/trace/README.md as
the upstream OSS documentation for
trace.go, and mention https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/647-apiserver-tracing (KEP-647: APIServer Tracing) as a possible future change to howkube-apiservertraces are generated (via OpenTelemetry).
Identifying Heavy API Server Clients from HTTP Access Logs
To identify which clients are generating the most load on kube-apiserver,
analyze the httplog.go HTTP access entries in apiserver component logs (an
optional feature that must be explicitly enabled via
--logging=SYSTEM,WORKLOADS,API_SERVER; always state this and link to
https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs#control_plane_logs):
- Very stable
httplog.golog structure (always mention this stability and show an example log line): Explicitly advise the user that the structure ofkube-apiserverhttplog.gologs is very stable across Kubernetes releases (making regex extraction and Log Analytics queries reliable), and include this example log line:I1015 11:36:56.835535 10 httplog.go:137] "HTTP" verb="GET" URI="/api/v1/namespaces/default/pods" latency="7.374935s" userAgent="my-controller/v1.0.0 (linux/amd64)" audit-ID="11111111-2222-3333-4444-555555555555" srcIP="10.0.0.1:12345" apf_pl="workload-low" apf_fs="everybody" apf_iseats=1 apf_fseats=0 apf_additionalLatency="0s" apf_execution_time="7.374765s" resp=200 - Key fields for client load analysis:
user_agent(userAgentin raw log text): Identifies the client binary, controller, or operator issuing the requests.verb: Distinguishes expensive request types (such as cluster-wideLISTor mutatingPATCH/UPDATEcalls) from lightweightGETcalls.apf_iseats(along withapf_fseatsandapf_execution_time): Reports the API Priority and Fairness (APF) initial concurrency seats occupied by the request; weighting or summingapf_iseats * apf_execution_timebyuser_agentandverbreveals which clients consume the most API server concurrency capacity.- Noisy-neighbor API load attribution and heavy
LISTclients from Cloud Audit Logs,kube-apiserverlogs,Trace[logs, and per-resource size metrics: Becauseapiserver_request_totalquantifies QPS spikes while Cloud Audit Logs attribute requests to callers even when optionalAPI_SERVERlogs are off, query GKE Cloud Audit Logs (cloudaudit.googleapis.com/activityanddata_access),kube-apiserverlogs (resource.type="k8s_control_plane_component"andresource.labels.component_name="apiserver"), and slow-requestTrace[logs (textPayload:"Trace[", recordingurl,user-agent,client, andtotal time) aggregated byprotoPayload.authenticationInfo.principalEmail(user),protoPayload.requestMetadata.callerSuppliedUserAgent(user-agent), and target namespace/resource, and correlate offender attribution withapiserver_request_total(grouped byverb,resource, andcode) plusapiserver_resource_size_estimate_bytes(orkubernetes.io/master/apiserver/resource_size_estimate_bytes, grouped bygroupandresource),apiserver_response_sizes, andapiserver_watch_list_duration_secondsto throttle/fix high-QPS clients and paginate or cache expensive cluster-wideLISTqueries (such asexternal-dnsor custom controllers). - Aggressive polling and APF saturation (
429/504/404): When workloads or CI runners see429 Too Many Requestsor504 Gateway Timeout(context canceled), query the APF metricsapiserver_flowcontrol_rejected_requests_total,apiserver_flowcontrol_current_inqueue_requests,apiserver_flowcontrol_request_wait_duration_seconds, andapiserver_flowcontrol_priority_level_seat_utilization(grouped bypriority_levelandflow_schema) alongsideapiserver_request_total(by status code404/504/429and verbGET/LIST), and enable control-plane logging (API_SERVERvia--logging=SYSTEM,WORKLOAD,API_SERVER) to pull detailed information onuser_agent(userAgent), target resources (URI/requestURI), and source IPs (src_ip/srcIP/sourceIPs) fromkube-apiserverlogs (or Cloud Audit Logs) to identify clients flooding the cluster with unpaginatedLISTcalls, tight404GETpolling loops, or single-digit millisecond?timeout=requests; replace tightGET/LISTpolling loops withSharedInformerwatches, add exponential backoff and client-side caching to noisy workloads (such as CI runners or bursty pod creators), increase overly short client request timeouts, or isolate noisy clients into a dedicatedFlowSchemaandPriorityLevelConfiguration.
Alerting
Set up alerts for critical conditions:
| Condition | Metric | Threshold |
|---|---|---|
| High API server latency | apiserver_request_duration_seconds |
P99 > 5s |
| Pod crash loops | kube_pod_container_status_restarts_total |
> 5 in 10min |
| Node not ready | kube_node_status_condition |
condition=Ready, status!=True |
| High GPU utilization | DCGM_FI_DEV_GPU_UTIL |
> 95% sustained |
| PVC near capacity | kubelet_volume_stats_used_bytes / capacity |
> 85% |
| Scheduling failures | scheduler_schedule_attempts_total{result="error"} |
> 0 |
Prerequisite: The
kube_*series above (e.g.,kube_pod_status_phase,kube_pod_container_status_restarts_total,kube_node_status_condition) come from kube-state-metrics, which GKE does not collect by default. Deploy the Managed Prometheus kube-state-metrics package first.
Proposing Dashboards & Alerts (Production Rules)
When designing or proposing alerting and dashboard strategies for GKE:
- Always explicitly name Google Cloud Monitoring as the platform to implement these alerts and dashboards.
- Always include API server latency (via
apiserver_request_duration_secondsmetric) on the dashboard as a critical indicator of control plane health, alongside node CPU/Memory and pod crash loops.
Node Health (Production Rules)
A comprehensive assessment of node health relies on analyzing these two metrics together:
kubernetes.io/node/status_condition(filtered bystatus_condition="Ready"): Use this to track healthy nodes. Note that it will only report values for nodes that have successfully bootstrapped.compute.googleapis.com/instance_group/size(filtered byinstance_group_name="gke-<cluster_name>-.*"): Use this to track the total number of nodes in a specific cluster. Note that it does not differentiate between healthy and unhealthy nodes.- Node registration failures (
AUTO_REPAIR_NODES): When new node pools fail registration before reportingkubernetes.io/node/status_condition, query the consumer project's Cloud Audit Logs (cloudaudit.googleapis.com/activity) for GCE instance creation denials (403/constraints/gcp.resourceLocations), verify that Private Google Access (privateIpGoogleAccess) is enabled on the cluster subnet, and check VPC routes and firewall rules to ensure traffic to*.googleapis.com,*.gcr.io, and*.pkg.devis not blackholed into a custom VPN or firewall. - Node labels overwritten on upgrade (
kubectl label nodevs. Node Pool API):gcp-controller-managerreconciles node labels declared in the GKE Node Pool API specification during control-plane upgrades and node repairs (observable viasystem:gcp-controller-managernode patches in Cloud Audit Logs), reverting manualkubectl label node <node> <key>=<val> --overwriteedits on GKE-managed label keys. Always update node pool labels persistently viagcloud container node-pools update <pool> --node-labels=...(or Terraformnode_config.labels).
Control Plane Health (Production Rules)
To check whether Google considers a GKE cluster's control plane healthy, use the
kubernetes.io/cluster/kcp_healthchecks system metric (on the k8s_cluster
monitored resource, included in the default SYSTEM metrics package):
- Metric semantics:
kubernetes.io/cluster/kcp_healthchecksis an incremental (DELTA/CUMULATIVEcounter) metric sampled every 60 seconds that counts Google-internal control plane probes, labeled by booleansuccess("true"or"false"). - Charting health ratio: Because the metric is an incremental counter
rather than a boolean gauge, chart control plane availability by dividing
the rate of successful checks (
success="true") by the overall rate of checks across allsuccessvalues:
sum by (project_id, location, cluster_name) (
rate(
kubernetes_io:cluster_kcp_healthchecks{
monitored_resource="k8s_cluster", success="true"
}[5m]
)
)
/
sum by (project_id, location, cluster_name) (
rate(
kubernetes_io:cluster_kcp_healthchecks{
monitored_resource="k8s_cluster"
}[5m]
)
)
- Ruling out a GKE control-plane outage (
kcp_healthchecksinnocence): Checkkubernetes.io/cluster/kcp_healthchecks(calculating the ratio of successful checks to total checks) alongsideapiserver_request_duration_secondsandapiserver_request_total(code="429"/5xx) in Cloud Monitoring. Whenkubernetes.io/cluster/kcp_healthchecksand API server latency are healthy with no429throttling, slow pod deletions or client delays originate from client-side request concurrency, pod finalizers/graceful termination, or the customer's own pod-creating service rather than a GKE control-plane fault. - Correlating with scheduled GKE maintenance windows, zonal resizes, and
cluster access errors (
kubernetes.io/cluster/in_maintenance_window): Query thekubernetes.io/cluster/in_maintenance_windowmetric in Cloud Monitoring (and check GKE cluster operations viagcloud container operations listor Cloud Audit Logs forRESIZE_CLUSTERorUPGRADE_MASTER) to verify whether brief API server unavailability or controller lease-loss alerts occurred during an active scheduled maintenance window or control plane resize. Adjust the cluster's configured maintenance window to a lower-traffic period or usekubernetes.io/cluster/in_maintenance_windowto suppress transient maintenance alerts. Note that zonal clusters have a single control-plane replica that experiences expected 15–30 minute API downtime during control-plane resizes and upgrades (mitigated by migrating to a regional cluster). Ifkubectlfails withEOForCLOUD_KMS_KEY_ERROR, checkgcloud container clusters describe(masterAuthorizedNetworksConfig,databaseEncryption, and cluster conditions) and project IAM/APIs to resolve client IP allowlist blocks (EOF), disabled Cloud KMS keys (CLOUD_KMS_KEY_ERROR), a disabledcontainer.googleapis.comAPI, or missing GKE service agent IAM bindings.
Cost Considerations
Monitoring and logging have associated costs:
- Cloud Logging: Charged per GiB ingested beyond free tier (50 GiB/project/month)
- Cloud Monitoring: Free for GKE system metrics; custom metrics charged per time series
- Managed Prometheus: Charged per samples ingested
To reduce costs in non-production:
# Reduce to system-only monitoring
gcloud container clusters update <CLUSTER_NAME> --region <REGION> \
--monitoring=SYSTEM \
--quiet
Distributed Tracing & Continuous Profiling (Recommended)
Not golden path defaults — recommended for production microservice architectures and performance-sensitive workloads.
- Cloud Trace: Add OpenTelemetry SDK to your app with the
opentelemetry-operations-go(or equivalent) exporter. Traces appear in Cloud Trace console. Identifies cross-service latency bottlenecks. - Cloud Profiler: Add the Cloud Profiler agent to your app. Profiles CPU and memory usage in production with low overhead. Identifies hotspots and compares across versions.
Recent additions:
- Managed OpenTelemetry for GKE (Preview): Managed in-cluster OTLP
endpoint plus auto-instrumentation for traces, metrics, and logs. Requires
GKE 1.34.1-gke.2178000+; enable with
gcloud beta container clusters update ... --managed-otel-scope=COLLECTION_AND_INSTRUMENTATION_COMPONENTS. - PSI (Pressure Stall Information) metrics: cAdvisor
container_pressure_{cpu,memory,io}_{waiting,stalled}_seconds_totalseries (beta in Kubernetes 1.34) can be collected via a Managed PrometheusClusterNodeMonitoringresource; GKE's documented collection path requires GKE 1.35+.
LQL Query Examples
Common Logging Query Language patterns for GKE troubleshooting:
# Error logs for a specific container
resource.type="k8s_container" AND resource.labels.container_name="my-app" AND severity>=ERROR
# OOMKilled events
resource.type="k8s_event" AND jsonPayload.reason="OOMKilling"
# Pod scheduling failures
resource.type="k8s_event" AND jsonPayload.reason="FailedScheduling"
# Audit logs (who did what)
resource.type="k8s_cluster" AND logName:"cloudaudit.googleapis.com"
Troubleshooting Managed Prometheus (GMP)
Diagnose GMP ingestion, rule, and query problems. Stay read-only (kubectl get
/ describe / logs) and propose config changes; do not mutate live resources
directly.
First: split ingestion-side vs query-side
Before anything else, query the up metric in the Metrics Explorer PromQL
tab in Cloud Monitoring. If up returns data, ingestion works and the problem
is query-side (Grafana / PromQL / permissions). If up is empty, the problem is
ingestion-side (collectors, scrape config, or write permission).
Ingestion-side
-
Check GMP system pods. They run in
gmp-systemon Standard clusters andgke-gmp-systemon Autopilot. Look forgmp-operator,collector(DaemonSet), andrule-evaluatornotRunningor with high restarts:kubectl get pods -n gmp-system # gke-gmp-system on Autopilot kubectl logs -n gmp-system -l app.kubernetes.io/name=collector -c prometheusA collector in
CrashLoopBackOffwithOOMKilledusually means high metric cardinality - drop unneeded series/labels (see cost section below) or apply a VPA to the collector. -
Check PodMonitoring / ClusterPodMonitoring. The three classic mistakes:
spec.selector.matchLabelsdoes not match the target Pod labels.- A
PodMonitoringonly discovers targets in its own namespace - useClusterPodMonitoringfor cluster-wide scope. spec.endpoints.portmust reference the named container port (e.g.port: web), not the port number.
-
Enable target status for scrape errors. Propose patching
OperatorConfigingmp-publicwithfeatures.targetStatus.enabled: true; once applied,kubectl describe podmonitoring <name>and readActive Targets,Unhealthy Targets, andLast Error(for exampleconnection refused, HTTP 404,context deadline exceeded). Disable it again when done - it can OOM the operator on large clusters.
Permissions (403 / no data written)
GMP components inherit the node service account. Ingestion needs
roles/monitoring.metricWriter (error Permission monitoring.timeSeries.create denied in collector logs); the rule-evaluator and query paths need
roles/monitoring.viewer (403 / PermissionDenied). If a query app (like
Grafana) uses Workload Identity, the bound Google service account also needs
roles/monitoring.viewer.
Rule and alert evaluation
Rule scope is decided by the resource kind: Rules (single namespace),
ClusterRules (whole cluster), and GlobalRules (all data in the metrics
scope). You must use GlobalRules to write rules against Cloud Monitoring
metrics - a Rules/ClusterRules resource silently returns no data for them.
Check rule-evaluator logs (-c evaluator) for parse/permission errors.
Query-side (Grafana / PromQL)
- Data source must point at the GMP frontend query proxy, not
localhost:9090, and the HTTP Method must be GET -POSTfails withno match[] parameter provided. - Grafana template variables: use the two-argument form
label_values(<metric>, <label>); the single-argumentlabel_values(<label>)is not supported by the GMP API. - Cloud Monitoring metrics that exist for multiple resource types need a
monitored_resourcelabel matcher, otherwise the query fails withseries selector must specify a label matcher on monitored resource name.
Cost, cardinality, and quota
Use the Cloud Monitoring Metrics Management page to find the metrics driving
billable samples and high cardinality. Reduce them with metricRelabeling in
the PodMonitoring (action: drop for whole metrics, action: labeldrop for
unbounded labels like user_id/request_id) or by raising the scrape
interval. 429 / RESOURCE_EXHAUSTED errors mean you have hit the Cloud
Monitoring API ingestion or query quota - optimize first, then request a quota
increase.
Supporting Links
Facts
- Kind
- Skill
- Repo
- google/skills
- Group
- Uncategorized
- Installs
- 8.1k
- Stars
- 21.7K