AKS Hour 4: Scaling and Node Management
- Design a node pool topology for a production cluster: a dedicated system pool (
CriticalAddonsOnly=true:NoSchedule) plus user pools split by workload. Choose VM size,--max-pods, OS SKU (Ubuntu or Azure Linux 3.0), and availability zones (zone-spanning and zone-aligned), and calculate a node's allocatable resources. - Explain how the Cluster Autoscaler (CA) decides when to scale up and down. Know the defaults and tuning direction for the dozen-plus parameters in
--cluster-autoscaler-profile(scan-interval 10s, scale-down-unneeded-time 10m, utilization-threshold 0.5, expander random, and so on). Diagnose why it does or doesn't scale, usingcluster-autoscaler-statusand events. - Understand Node Auto Provisioning (NAP): AKS-managed Karpenter. It uses a
NodePool(karpenter.sh/v1) and anAKSNodeClass(karpenter.azure.com/v1beta1) to pick VM SKUs directly based on what Pending Pods need. Know its network requirements, limits, consolidation, drift, and disruption budgets. - Combine HPA, the KEDA add-on (
--enable-keda), and the VPA add-on (--enable-vpa, includingInPlaceOrRecreate) at the pod level, and understand how they chain with node scaling. - Run special workloads on a Spot node pool (
--priority Spot --eviction-policy Delete --spot-max-price -1) and a GPU node pool (AKS-managed GPU:--enable-managed-gpu; self-managed:--gpu-driver none), and isolate them with taints and tolerations. - Protect myapp with PDBs, topologySpreadConstraints, and zone redundancy, and find 10 common mistakes in the scaling review.
1-hour timetable
| # | Time | Module | Core content | Animation / interactive | Lab (rg-aks-lab) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up: capacity planning | Reuse aks-lab and myapp, check node pools, calculate total requests | Capacity planning calculator | Export current node pool manifests |
| 1 | 00–06 | Node pool design: VM sizes, OS, and availability zones | system/user pools, VM families, maxPods and allocatable, Azure Linux 3.0, zone-spanning vs zone-aligned, immutable properties | Node pool designer (allocatable calculation) | Add an Azure Linux user pool (3 availability zones) |
| 2 | 06–13 | Cluster Autoscaler | Scale-up/scale-down algorithm, simulated scheduling, full profile parameters, expanders, balance-similar-node-groups, logs and status ConfigMap | CA scale-down timer simulator | Trigger scale-up with a load test, then adjust the profile and watch scale-down |
| 3 | 13–21 | Node Auto Provisioning (Karpenter) | NodePool / AKSNodeClass / NodeClaim, SKU selectors, limits/weight, consolidation, drift, budgets, limitations | Core animation: how Pending Pods drive the CA vs NAP scale-up decision | Custom NodePool on aks-lab-nap |
| 4 | 21–28 | HPA, KEDA add-on, and VPA | HPA formula and behavior, KEDA ScaledObject and scale to zero, VPA modes and InPlaceOrRecreate, conflicts among the three | HPA formula + KEDA queue scaling simulator | myapp HPA + KEDA cron scaling + VPA recommendations |
| 5 | 28–35 | Spot node pools and cost optimization | Spot pricing and eviction, automatic taints, tolerations + affinity, fallback to regular pools, priority expander, cost levers | Spot eviction and fallback simulator | Add a Spot pool and run an interruptible Job |
| 6 | 35–42 | GPU and dedicated workloads | AKS-managed GPU (driver + device plugin + DCGM), driver only, BYO (GPU Operator), MIG, taint isolation, scale to zero | GPU scheduling chain animation | (Optional, high cost) T4 GPU pool + nvidia-smi |
| 7 | 42–50 | PDBs, topology spread, and zone redundancy | PDBs and the Eviction API, topologySpread across zones and nodes, ZRS disks, zone failure drill | Availability zone failure simulator | myapp across 3 zones + PDB + drain drill |
| 8 | 50–60 | Scaling review and common mistakes | Review checklist, 10 common mistakes, metrics and alerts, troubleshooting decision tree | Scaling review scorer + troubleshooting tree | Run a review on aks-lab |
| — | After class | Cheat sheet · Capstone lab | Build an elastic, cost-efficient, zone-failure-resilient node and pod scaling setup for myapp | Final quiz (12 questions) | Capstone lab |
Knowledge coverage matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Design a node pool (size, OS, maxPods, availability zones) | ✓ | · | ✓ | · | ✓ | ✓ | ✓ | ✓ | az aks nodepool add | Azure Linux pool |
| Calculate allocatable and capacity | ✓ | ✓ | · | · | · | · | · | ✓ | kubectl describe node | Module 0/1 |
| Enable and tune Cluster Autoscaler | · | ✓ | · | · | ✓ | ✓ | · | ✓ | --cluster-autoscaler-profile | Scale up / scale down |
| Use NAP (NodePool/AKSNodeClass) | · | · | ✓ | · | ✓ | ✓ | · | ✓ | --node-provisioning-mode Auto | aks-lab-nap |
| Pod horizontal, vertical, and event-driven scaling | · | · | · | ✓ | · | · | · | ✓ | kubectl autoscale, ScaledObject, VPA | myapp HPA/KEDA |
| Spot and cost optimization | · | ✓ | ✓ | · | ✓ | · | · | ✓ | --priority Spot | Spot Job |
| GPU node pool | · | · | ✓ | · | · | ✓ | · | · | --enable-managed-gpu | nvidia-smi |
| PDB / topology spread / zone redundancy | ✓ | ✓ | ✓ | · | · | · | ✓ | ✓ | kubectl get pdb, drain | drain drill |
| Scaling troubleshooting | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | events, cluster-autoscaler-status, nodeclaims | Troubleshooting tree |
What this hour leaves out (and where to learn it)
| Topic | Why it's not in this hour | Where to learn it |
|---|---|---|
| requests/limits, QoS, scheduler Filter/Score, general affinity and taint semantics | General Kubernetes concepts that this hour uses directly | K8s Hour 2 |
| General principles of HPA / VPA and metrics-server | This hour only covers AKS add-ons and how they link to nodes | K8s Hour 6 (autoscaling) |
| Node pool upgrades, surge, node images, and maintenance windows | Belongs to upgrades and operations | AKS Hour 6 |
| Subnet IP exhaustion and SNAT port exhaustion effects on scale-up | Belongs to deep troubleshooting | AKS Hour 2 (networking) · Hour 7 |
| Deploying myapp with Helm, managed Prometheus metrics collection | Tool details are covered in other courses | Helm Hour 3 · Prometheus Hour 3 |
| KAITO, DRA, Kueue + ProvisioningRequest, and other AI batch scheduling | Beyond 1 hour | The ProvisioningRequest section of the CA docs |
How to use this course
Principles · diagrams · animation · commands · lab · production case · troubleshooting · quiz · voice · video. Read “Principles” and “Animation” first, then do the “Lab”. The animation in module 3 is the core of this hour.
A module counts toward progress when you score ≥ 70% on its quiz or click “Mark this module complete”. Progress is saved in localStorage in this browser (it is cleared on refresh if local storage is disabled).
The “Voice” tab uses the browser's built-in Web Speech API (en-US) to read the narration script aloud. Without an English voice pack, the script can still be read or passed to a TTS tool.
--os-sku Ubuntu defaults to Ubuntu 24.04 on 1.35+; --os-sku AzureLinux defaults to Azure Linux 3.0 on 1.32+. Azure Linux 2.0 reached end of support on 2025-11-30, and its images were deleted from 2026-10-31, so pools still on it can no longer scale up. Costs are hourly example estimates; check the Azure pricing calculator for current prices.aks-lab, ACR, myapp) and are familiar with the scheduling and scaling concepts in the Kubernetes 8 + 1 hour course.Module 0 · Warm-up: capacity planning (complete before class)
- Your subscription has the resource group
rg-aks-lab(canadacentral), the clusteraks-lab(Standard tier, Azure CNI Overlay), and ACRacraks<suffix>. The namespacemyappruns myapp (Flask + gunicorn, port 5000,/healthz) and Redis. - Locally: Azure CLI ≥ 2.85 (
--enable-managed-gpuneeds 2.85; NAP needs ≥ 2.76;--gpu-driverneeds ≥ 2.72.2), and kubectl within one minor version of the cluster version. - Azure role: Contributor on the resource group (or Azure Kubernetes Service Contributor + Network Contributor), plus RBAC permission in the cluster to create namespace-scoped objects.
Step 1: Set variables and check the cluster
RG=rg-aks-lab; LOC=canadacentral; CLUSTER=aks-lab
az account show --query "{sub:name, id:id}" -o table
az aks show -g $RG -n $CLUSTER --query "{k8s:kubernetesVersion, tier:sku.tier, plugin:networkProfile.networkPlugin, mode:networkProfile.networkPluginMode, dataplane:networkProfile.networkDataplane, power:powerState.code}" -o table
az aks get-credentials -g $RG -n $CLUSTER --overwrite-existing
az aks nodepool list -g $RG --cluster-name $CLUSTER \
--query "[].{name:name, mode:mode, vm:vmSize, count:count, os:osSku, zones:join(',', availabilityZones || ['-']), maxPods:maxPods, autoscale:enableAutoScaling, min:minCount, max:maxCount}" -o table
K8s Tier Plugin Mode Dataplane Power ------ -------- -------- ------- ----------- ------- 1.36.5 Standard azure overlay azure Running Name Mode Vm Count Os Zones MaxPods Autoscale Min Max --------- ------ --------------- ------- ------ ------- --------- ----------- ----- ----- nodepool1 System Standard_D4s_v5 2 Ubuntu - 250 False
If the cluster was stopped with az aks stop, first run az aks start -g $RG -n $CLUSTER (about 5–10 min). Use the node pool name from the actual output of hour 1; below, the SYSPOOL variable refers to it: SYSPOOL=$(az aks nodepool list -g $RG --cluster-name $CLUSTER --query "[?mode=='System'].name | [0]" -o tsv).
Step 2 (only if the cluster was deleted): quickly rebuild aks-lab and myapp
az group create -n $RG -l $LOC az aks create -g $RG -n $CLUSTER -l $LOC --tier standard \ --kubernetes-version 1.36 \ --network-plugin azure --network-plugin-mode overlay --pod-cidr 192.168.0.0/16 \ --node-count 2 --node-vm-size Standard_D4s_v5 \ --enable-managed-identity --generate-ssh-keys ACR=acraks$RANDOM; az acr create -g $RG -n $ACR --sku Basic az aks update -g $RG -n $CLUSTER --attach-acr $ACR # From the myapp directory in the Docker course: az acr build -r $ACR -t myapp:1.0 . az aks get-credentials -g $RG -n $CLUSTER --overwrite-existing kubectl create namespace myapp
apiVersion: apps/v1
kind: Deployment
metadata: { name: redis, namespace: myapp, labels: { app: redis } }
spec:
replicas: 1
selector: { matchLabels: { app: redis } }
template:
metadata: { labels: { app: redis } }
spec:
containers:
- name: redis
image: redis:7-alpine
ports: [ { containerPort: 6379 } ]
resources: { requests: { cpu: 50m, memory: 64Mi }, limits: { memory: 128Mi } }
---
apiVersion: v1
kind: Service
metadata: { name: redis, namespace: myapp }
spec: { selector: { app: redis }, ports: [ { port: 6379 } ] }
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: myapp, namespace: myapp, labels: { app: myapp } }
spec:
replicas: 3
selector: { matchLabels: { app: myapp } }
template:
metadata: { labels: { app: myapp } }
spec:
containers:
- name: myapp
image: ACR_NAME.azurecr.io/myapp:1.0 # replace with $ACR
ports: [ { containerPort: 5000 } ]
env: [ { name: REDIS_HOST, value: redis } ]
readinessProbe: { httpGet: { path: /healthz, port: 5000 }, periodSeconds: 5 }
resources: { requests: { cpu: 250m, memory: 256Mi }, limits: { memory: 512Mi } }
---
apiVersion: v1
kind: Service
metadata: { name: myapp, namespace: myapp }
spec: { selector: { app: myapp }, ports: [ { port: 80, targetPort: 5000 } ] }
sed "s/ACR_NAME/$ACR/" myapp-base.yaml | kubectl apply -f - kubectl -n myapp rollout status deploy/myapp
az aks stop -g $RG -n $CLUSTER; when the whole course is finished: az group delete -n $RG --yes --no-wait. Note: clusters with NAP enabled cannot be stopped, which is why module 3 uses a separate cluster, aks-lab-nap.Step 3: Take inventory of total requests (input for capacity planning)
# Allocatable and allocated requests per node
kubectl get nodes -o custom-columns=NAME:.metadata.name,CPU:.status.allocatable.cpu,MEM:.status.allocatable.memory,PODS:.status.allocatable.pods,ZONE:.metadata.labels.topology\\.kubernetes\\.io/zone
kubectl describe nodes | grep -A6 "Allocated resources"
# Total requests in the myapp namespace
kubectl -n myapp get pod -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[*].resources.requests.cpu}{"\t"}{.spec.containers[*].resources.requests.memory}{"\n"}{end}'
NAME CPU MEM PODS ZONE aks-nodepool1-31415926-vmss000000 3860m 12557688Ki 250 0 aks-nodepool1-31415926-vmss000001 3860m 12557688Ki 250 0 ... cpu 1460m (37%) 3200m (82%) memory 2306Mi (18%) 5754Mi (46%)
A ZONE of 0 means the node pool doesn't use availability zones (a regional pool). D4s_v5 has 4 vCPU / 16 GiB: CPU reservation 140m, so allocatable is 3860m. Memory reservation = min(20MB × maxPods + 50MB, 25% of memory) + 100Mi eviction threshold. With maxPods=250, 20×250+50=5050MB is larger than 25% (4 GiB), so the 25% cap applies and allocatable is about 12 GiB. Module 1 explains why you should lower --max-pods.
Capacity planning calculator
Enter the workload's replica count and per-replica requests, pick a node size, and calculate how many nodes you need (including N+1 redundancy and a 70% target utilization). Allocatable for each size is calculated with the AKS 1.29+ reservation formula.
Warm-up: answer from memory (30 seconds)
What value does the scheduler compare on a node?
Allocatable versus the sum of requests of scheduled pods, not actual usage (K8s hour 2). This is also how Cluster Autoscaler and NAP decide a pod “won't fit”. Both run simulated scheduling.
Which Azure resource does an AKS node pool map to, and in which resource group?
In the node resource group MC_rg-aks-lab_aks-lab_canadacentral, each node pool corresponds to one VMSS. (NAP nodes are standalone VMs, not part of a VMSS.) Don't manually change a VMSS's instance count or autoscale settings.
HPA scaled out, and the new pods are Pending. Who adds nodes?
HPA only changes the replica count. Nodes are added by the Cluster Autoscaler (per node pool, by changing VMSS capacity) or by NAP (which creates VMs of a suitable SKU directly). That is the topic of modules 2 and 3.
Module 1 · Node pool design: VM sizes, OS, and availability zones
- Tell system and user node pools apart. Know the hard limits for system pools (Linux, ≥ 2 nodes, ≥ 4 vCPU / 4 GB, B-series not supported, maxPods ≥ 30) and the recommendations (3 nodes,
CriticalAddonsOnly=true:NoSchedule). - Choose a VM family (D/E/F/L/N) and size based on workload shape. Understand how
--max-podsaffects memory reservation, subnet IPs, and density, and be able to calculate allocatable. - Choose an OS SKU (
Ubuntu,AzureLinux, or versioned SKUs) and an availability zone model (zone-spanning, zone-aligned, regional). Remember which properties cannot be changed after creation.
What: what a node pool is
AKS groups nodes with the same configuration into node pools (agent pools). Each pool corresponds to one Virtual Machine Scale Set in the node resource group, with the same VM size, OS SKU, Kubernetes version, maxPods, labels, taints, and availability zone settings. There are two pool modes:
System pool (--mode System) | User pool (--mode User, the default for nodepool add) | |
|---|---|---|
| Purpose | Critical system pods such as CoreDNS, metrics-server, konnectivity, and CSI controllers | Business workloads |
| OS | Linux only (Ubuntu / Azure Linux) | Linux or Windows |
| Node count | At least 2, 3 recommended (spread across availability zones) | 0 or more (can scale to 0) |
| Size | ≥ 4 vCPU and ≥ 4 GB; B-series not supported; recommended 3×8 vCPU or 2×16 vCPU (large clusters) | Official note: sizes with fewer than 2 vCPU / 2 GB may not be available |
| Labels / taints | Automatic kubernetes.azure.com/mode: system; adding CriticalAddonsOnly=true:NoSchedule is recommended | kubernetes.azure.com/mode: user |
| Count | At least 1 per cluster | Up to 100 pools per cluster, 1000 nodes per pool, 5000 nodes per cluster |
Why: why use multiple node pools
- Isolation: a memory leak in a business pod won't crowd out CoreDNS. GPU, Spot, and Windows workloads can only run in their own pools.
- Scaling granularity: Cluster Autoscaler scales per node pool, and each pool has its own min/max. If everything is mixed into one pool, the whole pool can only grow together.
- Immutable properties: VM size, OS disk type, availability zones, Spot priority, taints (set at creation), and GPU configuration cannot be changed in place. Changing the size means creating a new pool, migrating, and deleting the old pool. A multi-pool design lets you do this smoothly.
How: choose size, maxPods, and allocatable
| VM family | Characteristics | Typical use |
|---|---|---|
| Dsv5 / Ddsv5 / Dasv5 / Dpsv6 (Arm64) | General purpose, vCPU:memory = 1:4 | Most web and API workloads (myapp) |
| Esv5 / Edsv5 | Memory optimized, 1:8 | Caches, large JVM heaps, database proxies |
| Fsv2 | Compute optimized, 1:2 | CPU-intensive batch work, encoding |
| Lsv3 | Local NVMe storage optimized | Local-disk scenarios such as Kafka and Elasticsearch |
| NC / ND / NV (NVIDIA) | GPU; AKS minimum recommendation Standard_NC4as_T4_v3 | Inference, training (module 6) |
Node reservation (AKS 1.29+): the CPU reservation follows a tiered schedule by core count: 1 core 60m, 2 cores 100m, 4 cores 140m, 8 cores 180m, 16 cores 260m, 32 cores 420m, 64 cores 740m. Memory reservation = min(20MB × maxPods + 50MB, 25% × memory), plus the kubelet hard eviction threshold memory.available < 100Mi. So the higher maxPods is, the more memory is reserved. A D4s_v5 (16 GiB) reserves at most 4 GiB at maxPods=250, but only 2.25 GB at maxPods=110.
The other side of maxPods is IP addresses: with Azure CNI Overlay, pod IPs come from the pod CIDR (192.168.0.0/16 in this course), and each node uses only one subnet IP. The default maxPods is 250. With traditional Azure CNI (node subnet), each node pre-allocates maxPods subnet IPs (default 30). Subnet exhaustion during scale-out is a common incident (hours 2 and 7).
OS SKU choice
--os-sku | Behavior | Recommendation |
|---|---|---|
Ubuntu | Picks the OS version automatically based on the K8s version: 1.25–1.34 uses 22.04, 1.35+ uses 24.04 | Default choice; the OS follows automatically when you upgrade K8s |
AzureLinux | 1.27–1.31 uses Azure Linux 2.0, 1.32+ uses Azure Linux 3.0 | Smaller images and attack surface, Microsoft-built kernel; the default for AKS Automatic system pools |
Ubuntu2404 / Ubuntu2204 / AzureLinux3 | Versioned SKU with a fixed OS version (Ubuntu2404 supports 1.32–1.38; AzureLinux3 supports 1.28–1.36) | Use only for early testing or rollback. Afterward you must manually move back to the default SKU, or it will block K8s upgrades. |
AzureContainerLinux / Flatcar | Immutable OS (1.34+ / all versions) | For special compliance scenarios. Note that GPU is not supported on Flatcar. |
Linux pools can migrate in place with az aks nodepool update --os-sku (this rebuilds the images). Ubuntu 22.04 is supported until 2027-06-30. Azure Linux 2.0 reached end of support on 2025-11-30, and its images were deleted from 2026-10-31, so pools still on it can no longer scale up.
Availability zone model
- Zone-spanning (
--zones 1 2 3): one pool spans three zones, and AKS automatically balances node counts across the zones. This is the simplest option and suits stateless services. - Zone-aligned (one pool per zone,
--zones 1/2/3): works better with CA. When zone-aware scheduling is involved, such as volume topology for LRS disks, CA can scale a specific zone precisely. The official recommendation is to enable the profile'sbalance-similar-node-groupsin this case. - Regional (no zones specified): no cross-zone guarantee. A zone failure may affect everything.
- Availability zones cannot be changed after creation. Nodes deployed across zones carry no extra node charge (cross-zone traffic is billed separately).
--zones auto(automatic zone placement) is currently in preview.
When: typical topologies
- Small production: system pool of 3×D4s_v5 (3 zones, CriticalAddonsOnly) + one user pool (3 zones, CA 2–10).
- Medium to large: system pool + general user pool + memory-optimized pool + Spot batch pool + (optional) GPU pool. Or hand all user-side scaling to NAP (module 3).
Comparison with similar practices
| AKS node pool | EKS managed node groups / Karpenter | GKE node pool | |
|---|---|---|---|
| Underlying | VMSS (NAP nodes are standalone VMs) | Auto Scaling Group / EC2 Fleet | Managed Instance Group |
| Multiple sizes | One size per pool (NAP can use multiple SKUs) | Node groups can have multiple instance types; Karpenter is dynamic | One type per pool (NAP is dynamic) |
| System pool concept | Explicit mode=System | None, uses labels | None, uses labels |
--node-vm-size can only be set at creation, so changing the size means creating a new pool and migrating (hour 6 covers the resize procedure). ③ "Setting maxPods to 250 is the most cost-effective." Memory reservation grows linearly with maxPods (capped at 25%), which wastes capacity on small nodes. In node subnet mode it also pre-allocates many IPs. ④ "Turning on autoscaling for the VMSS in the Azure portal works too." The official docs explicitly forbid manual changes to VMSS scaling settings, because they conflict with CA.Architecture diagram: node pool topology of a production cluster
Data flow diagram: how the resources of one D4s_v5 are divided
Interactive simulator: node pool designer
Choose VM size, maxPods, availability zone model, and OS SKU. The simulator calculates allocatable with the AKS 1.29+ reservation formula. It estimates how many myapp replicas (250m / 256Mi) fit on each node and how much capacity remains if a zone fails. The terminal below shows the equivalent az aks nodepool add command and what the AKS RP does.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az aks nodepool add | Add node pool | --mode, --node-vm-size, --os-sku, --zones, --max-pods, --node-taints, --labels, --enable-cluster-autoscaler --min-count --max-count |
az aks nodepool update | Change mutable properties | --mode, --os-sku (migrate between Linux SKUs), --labels, --node-taints, autoscaler settings |
az aks nodepool scale | Set node count manually (when CA is not enabled) | --node-count |
az aks nodepool delete | Delete node pool (cordons and drains nodes) | A system pool must always keep at least one pool |
az aks list-vm-skus | Check SKU availability and zone support in a region | --location --size --all |
az vm list-usage | Check vCPU quota | Common causes of scale-out failure |
Add a user pool spanning 3 zones with Azure Linux
az aks nodepool add -g $RG --cluster-name $CLUSTER -n userpool \
--mode User --node-vm-size Standard_D4s_v5 --os-sku AzureLinux \
--zones 1 2 3 --node-count 3 --max-pods 110 \
--labels workload=general \
--enable-cluster-autoscaler --min-count 3 --max-count 9
az aks nodepool show -g $RG --cluster-name $CLUSTER -n userpool \
--query "{mode:mode, vm:vmSize, os:osSku, zones:availabilityZones, maxPods:maxPods, image:nodeImageVersion, min:minCount, max:maxCount}" -o jsonc
{
"image": "AKSAzureLinux-V3gen2-202611.03.0",
"max": 9,
"maxPods": 110,
"min": 3,
"mode": "User",
"os": "AzureLinux",
"vm": "Standard_D4s_v5",
"zones": [ "1", "2", "3" ]
}
How to verify: kubectl get nodes -L topology.kubernetes.io/zone,kubernetes.azure.com/os-sku,agentpool should show canadacentral-1/2/3. Common error: the chosen SKU is unavailable in a zone, so creation fails. Check first with az aks list-vm-skus -l canadacentral --size Standard_D4s_v5 --all -o table. Production use: separate business pools from the system pool, and use the workload label for nodeSelector.
Isolate the system pool
# Create a dedicated system pool (3 zones, with CriticalAddonsOnly taint) az aks nodepool add -g $RG --cluster-name $CLUSTER -n syspool \ --mode System --node-vm-size Standard_D4s_v5 --os-sku AzureLinux \ --zones 1 2 3 --node-count 3 --max-pods 110 \ --node-taints CriticalAddonsOnly=true:NoSchedule # Change the original pool to User (requires another System pool to exist) az aks nodepool update -g $RG --cluster-name $CLUSTER -n $SYSPOOL --mode User kubectl -n kube-system get pod -o wide | grep -E "coredns|metrics-server|konnectivity"
Changing the mode does not automatically migrate running system pods. They will be scheduled onto mode=system nodes the next time they are rebuilt. To move them immediately, kubectl drain the old nodes (subject to PDBs), or do it as part of the module 7 lab.
Migrate OS SKU (rebuilds images in place)
az aks nodepool update -g $RG --cluster-name $CLUSTER -n userpool --os-sku Ubuntu # Watch the rolling rebuild kubectl get nodes -L kubernetes.azure.com/os-sku -w
This command triggers node rebuilds (the same surge and drain process as upgrades, covered in hour 6). If no image exists for the target OS with the current K8s version or size, the command fails.
Lab 1: Design and create userpool, then move myapp to it (about 12 min; cloud resources about +0.6 USD/hour)
az aks list-vm-skus -l $LOC --size Standard_D4s_v5 --all -o table az vm list-usage -l $LOC -o table | grep -Ei "Total Regional vCPUs|DSv5"
Name ResourceType Locations Zones Restrictions --------------- --------------- ------------- ------- -------------- Standard_D4s_v5 virtualMachines canadacentral 1,2,3 None Total Regional vCPUs 8 100 Standard DSv5 Family vCPUs 8 50
kubectl get nodes -L agentpool,topology.kubernetes.io/zone,kubernetes.azure.com/os-sku
NAME STATUS ROLES AGE VERSION AGENTPOOL ZONE OS-SKU aks-nodepool1-31415926-vmss000000 Ready <none> 3d v1.36.5 nodepool1 0 Ubuntu aks-nodepool1-31415926-vmss000001 Ready <none> 3d v1.36.5 nodepool1 0 Ubuntu aks-userpool-27182818-vmss000000 Ready <none> 3m v1.36.5 userpool canadacentral-1 AzureLinux aks-userpool-27182818-vmss000001 Ready <none> 3m v1.36.5 userpool canadacentral-2 AzureLinux aks-userpool-27182818-vmss000002 Ready <none> 3m v1.36.5 userpool canadacentral-3 AzureLinux
kubectl -n myapp patch deploy myapp --type merge -p '{"spec":{"template":{"spec":{"nodeSelector":{"workload":"general"}}}}}'
kubectl -n myapp patch deploy redis --type merge -p '{"spec":{"template":{"spec":{"nodeSelector":{"workload":"general"}}}}}'
kubectl -n myapp rollout status deploy/myapp
kubectl -n myapp get pod -o wide
Verify: the NODE of every myapp pod is aks-userpool-*.
kubectl get nodes -o custom-columns=NAME:.metadata.name,POOL:.metadata.labels.agentpool,CPU:.status.allocatable.cpu,MEM:.status.allocatable.memory,PODS:.status.allocatable.pods
NAME POOL CPU MEM PODS aks-nodepool1-31415926-vmss000000 nodepool1 3860m 12557688Ki 250 aks-userpool-27182818-vmss000000 userpool 3860m 14160000Ki 110
On the same size of node, lowering maxPods from 250 to 110 frees about 1.5 GiB of allocatable memory (example value; use describe node for actual numbers).
az aks stop -g $RG -n $CLUSTER. To delete this pool: az aks nodepool delete -g $RG --cluster-name $CLUSTER -n userpool --no-wait.Case 1: CoreDNS is crowded out by business pods, and DNS resolution times out cluster-wide
Problem: there was a single 3-node pool. A release set very large requests, so CoreDNS was preempted and went Pending, and DNS timed out for all services. Approach: split out a dedicated system pool with CriticalAddonsOnly=true:NoSchedule, and move all business workloads to the user pool. Configuration: system pool of 3×D4s_v5 spanning 3 zones; user pool with CA enabled. Limitation: system pool nodes still need to run DaemonSets (CNI, CSI, monitoring agents), so don't choose a size that is too small.
Case 2: during scale-out, memory "disappears" by 25%
Problem: the team estimated capacity from VM memory, but each D2s_v5 (8 GiB) could fit only 70% of the expected pods. Approach: they found that Overlay defaults to maxPods=250, so the memory reservation hit the 25% cap (2 GiB). Configuration: replace the pool with a new one using maxPods=50 (maxPods cannot be changed in place): 20×50+50=1050MB reserved. Limitation: a maxPods that is too low makes services with many small pods (lots of sidecars) hit the pod count limit first, so balance it against the average pod size.
Case 3: an Azure Linux 2.0 pool suddenly cannot scale up in 2026-11
Problem: a long-unupgraded 1.31 cluster used AzureLinux (which defaulted to 2.0 at the time). After 2026-10-31, the node images were deleted, and all CA scale-ups failed. Approach: first run az aks nodepool update --os-sku AzureLinux3 (supported on 1.28–1.36) to move to 3.0, then upgrade K8s to a supported version, and finally switch back to the default AzureLinux SKU. Limitation: image rebuilds are constrained by PDBs and surge quota, so reserve vCPU quota in advance.
Common errors and fixes
Symptom: when you create a System pool with a B-series or 2 vCPU size, az returns BadRequest / InvalidParameter (the VM size does not meet system pool requirements)
Cause: system pools don't support B-series, and they require at least 4 vCPU / 4 GB. (The docs also note a general limit: sizes under 2 vCPU / 4 GB may not be available.)
az aks list-vm-skus -l $LOC --size Standard_D4s_v5 -o table
Fix: use D4s_v5 or larger for the system pool. Use B-series only for development and test user pools.
(ZonalAllocationFailed) Allocation failed. We do not have sufficient capacity for the requested VM size in this zone.
Cause: there is not enough capacity for this size in this zone (common with new sizes or GPUs).
az aks nodepool show -g $RG --cluster-name $CLUSTER -n userpool --query "{state:provisioningState, err:status}"
az aks list-vm-skus -l $LOC --size Standard_D4s_v5 --all -o table
Fix: switch to a similar size in the same family (such as Dds_v5 or Das_v5), change zones, or use NAP so it can pick from several SKUs. For critical capacity, use a capacity reservation group (CRG).
(QuotaExceeded) Operation could not be completed as it results in exceeding approved Total Regional Cores quota.
Cause: the regional vCPU quota or the quota for that VM family is insufficient. Note that upgrade surge, CA scale-up, and NAP all consume quota temporarily.
az vm list-usage -l $LOC -o table | sort -k2 -n -r | head
Fix: request a quota increase on the portal's Quotas page, or reduce surge and lower max-count.
Symptom: when you change the only System pool to User or delete it, the request is rejected (the cluster must keep at least one System pool)
Cause: only one System pool is left in the cluster.
Fix: first run az aks nodepool add --mode System to create a new one, then modify or delete the old pool.
Pod stuck Pending: 0/5 nodes are available: 3 node(s) had untolerated taint {CriticalAddonsOnly: true}, 2 Insufficient memory.
Cause: the system pool's taint is correctly blocking business pods, and the user pool doesn't have enough memory.
kubectl describe nodes -l agentpool=userpool | grep -A6 "Allocated resources"
Fix: don't add the CriticalAddonsOnly toleration to business pods. Enable CA on the user pool (module 2), or raise max-count.
1. List the name, mode, size, OS SKU, availability zones, and maxPods of all node pools.
az aks nodepool list -g $RG --cluster-name $CLUSTER --query "[].{name:name,mode:mode,vm:vmSize,os:osSku,zones:availabilityZones,maxPods:maxPods}" -o table2. Add a system pool that only runs system components and spans 3 zones.
az aks nodepool add -g $RG --cluster-name $CLUSTER -n syspool --mode System --node-vm-size Standard_D4s_v5 --zones 1 2 3 --node-count 3 --node-taints CriticalAddonsOnly=true:NoSchedule
The team wants to change the existing user pool from D4s_v5 to D8s_v5 and move from regional to 3 zones. How can they do this without downtime?
Size and availability zones are both immutable properties. Steps: ① create a new pool with D8s_v5 and --zones 1 2 3 (same labels, CA enabled); ② confirm that critical services have PDBs and at least 2 replicas; ③ kubectl cordon every node in the old pool, then kubectl drain --ignore-daemonsets --delete-emptydir-data them one by one so pods are recreated in the new pool; ④ once things are stable, delete the old pool. Watch the quota for the new pool and, in node subnet mode, the subnet IPs.
Verified instructional videos
Official documentation
- Use system node pools in AKS
- Limits for resources, SKUs, and regions
- Node resource reservations
- Upgrade OS version (OS SKU table)
- Configure availability zones in AKS
Video storyboard script (about 90 seconds)
This course file cannot generate a video or MP3 directly. A storyboard and narration script are provided, which you can hand to a video tool.
Visual: an AKS cluster is split into horizontal bands (system pool, user pool, Spot pool, GPU pool), each labeled with its VMSS below.
Narration: In AKS, a node pool is a virtual machine scale set. All nodes in the same pool share the same size, system, and labels.
Visual: the memory of a 16 GiB node is split into three sections: reserved, eviction threshold, and allocatable. Drag maxPods from 110 to 250, and the reserved section grows.
Narration: The more pods a node can run, the more system memory it reserves, up to 25 percent. The scheduler only sees the allocatable part.
Visual: three availability zones side by side. The nodes of a zone-spanning pool are spread evenly. Switch to one pool per zone.
Narration: Availability zones are chosen when the pool is created and can't be changed later. To scale precisely by zone, use one pool per zone and turn on balance-similar-node-groups.
Visual: a CriticalAddonsOnly taint appears on the system pool, and business pods are pushed back to the user pool.
Narration: Add the CriticalAddonsOnly taint to the system pool so that business workloads and system components stay isolated.
Module 2 · Cluster Autoscaler
- Explain the CA scale-up chain: unschedulable pod → simulated scheduling against each node pool's template node → expander picks a pool → VMSS capacity is changed → new node registers → scheduler binds the pod.
- Explain the scale-down criteria: utilization (max of CPU requests and memory requests, divided by allocatable) <
scale-down-utilization-threshold, sustained forscale-down-unneeded-time, and every pod can be placed elsewhere without being blocked by PDBs, local storage, or annotations. - Use
--enable-cluster-autoscaler,--update-cluster-autoscaler, and--cluster-autoscaler-profilefluently, and read thecluster-autoscaler-statusConfigMap, events, and control plane logs.
What: Cluster Autoscaler in AKS
CA is a component of the open-source kubernetes/autoscaler project. AKS runs it in the managed control plane, so you won't see its pods in kube-system. AKS manages its version according to the Kubernetes version (for example, 1.35/1.36 clusters use cluster-autoscaler v1.35.0-aks-*). Autoscaling is enabled per node pool, and each pool has its own --min-count/--max-count. The tuning parameters in --cluster-autoscaler-profile are cluster-wide: they apply to all CA-enabled pools at the same time and can't be set per pool.
Why: why it's needed
HPA and KEDA only add pod replicas. When the sum of requests exceeds the allocatable capacity of all nodes, new pods enter Pending (event FailedScheduling … Insufficient cpu), and someone has to add nodes. When the load drops, someone has to drain idle nodes safely and delete them. Those two jobs are what CA does.
How: scale-up and scale-down algorithm
Scale-up (every scan-interval, default 10 seconds)
- List pods with
PodScheduled=False, reason=Unschedulable. (new-pod-scale-up-delaycan ignore pods that are too new.) - For each CA-enabled node pool that hasn't reached max-count, build a "virtual new node" from the VMSS template (size, labels, taints, zone), then use the same Filter plugins as the scheduler to simulate whether the Pending pod would fit on it.
- When several pools qualify, the expander chooses:
random(AKS default),most-pods,least-waste, orpriority(requires thecluster-autoscaler-priority-expanderConfigMap in kube-system; follow the official docs). - Calculate how many nodes are needed, then call the Azure API to increase that VMSS's capacity. If
balance-similar-node-groupsis enabled, spread the increase across similar pools. - After the new VM starts, kubelet registers it and the node becomes Ready. Then kube-scheduler (not CA) binds the Pending pod to it. A node that isn't ready within
max-node-provision-time(default 15 minutes) is treated as failed, and CA falls back and tries other pools.
Scale-down
- Node utilization = max(sum of CPU requests of pods on the node / CPU allocatable, sum of memory requests / memory allocatable). Below
scale-down-utilization-threshold(default 0.5), the node becomes a candidate.ignore-daemonsets-utilizationdetermines whether DaemonSets count toward utilization. - Simulation: can every pod on the node be moved to other nodes? These conditions block scale-down: a PDB doesn't allow eviction; non-DaemonSet pods in kube-system (
skip-nodes-with-system-pods=true); pods use local storage withskip-nodes-with-local-storage=true; pod annotationcluster-autoscaler.kubernetes.io/safe-to-evict: "false"; node annotationcluster-autoscaler.kubernetes.io/scale-down-disabled: "true"; bare pods with no controller; or the node pool is already at min-count. - The node must be marked "not needed" continuously for
scale-down-unneeded-time(default 10 minutes), and more thanscale-down-delay-after-add(default 10 minutes) must have passed since the last scale-up. - Taint the node with
ToBeDeletedByClusterAutoscaler, then evict its pods through the Eviction API (respects PDBs and waits up tomax-graceful-termination-sec, default 600 seconds), then delete the VM. If the pool setsscaleDownMode: Deallocate, the VM is deallocated instead of deleted. Empty nodes can be deleted in bulk (max-empty-bulk-delete, default 10).
AKS profile parameters and defaults (verified 2026-11)
| Parameter | Default | Tuning direction |
|---|---|---|
scan-interval | 10s | Raise to 20–30s in large clusters to reduce API load |
scale-down-delay-after-add | 10m | Raise for bursty workloads to avoid scaling up and immediately back down |
scale-down-delay-after-delete | = scan-interval | — |
scale-down-delay-after-failure | 3m | — |
scale-down-unneeded-time | 10m | For 15-minute periodic jobs, set to 15–20m |
scale-down-unready-time | 20m | — |
scale-down-utilization-threshold | 0.5 | Raise to 0.6–0.7 to save more (more aggressive) |
ignore-daemonsets-utilization | false | Set to true when DaemonSets are heavy |
daemonset-eviction-for-empty-nodes / …-for-occupied-nodes | false / true | Adjust when DaemonSets need a graceful exit (such as log flushing) |
max-graceful-termination-sec | 600 | Should be ≥ the business terminationGracePeriodSeconds |
balance-similar-node-groups | false | Set to true when using one pool per zone |
expander | random | least-waste saves money; priority favors Spot |
skip-nodes-with-local-storage | false | Set to true if emptyDir holds data that must not be lost |
skip-nodes-with-system-pods | true | — |
max-empty-bulk-delete | 10 | Speeds up reclaiming after large batch jobs |
new-pod-scale-up-delay | 0s | When submitting batch Jobs in bulk, set 10–30s so the scheduler can catch up first |
max-total-unready-percentage / ok-total-unready-count | 45% / 3 | Once exceeded, CA stops acting (safety mechanism) |
max-node-provision-time | 15m | — |
When: when to use CA vs NAP
- CA: node sizes are fixed and known, you need VMSS-level stability and maturity, you need Windows node pools, you need
az aks stop, or you use networking such as kubenet/Calico that NAP doesn't support. - NAP (module 3): diverse workloads, you want the most suitable or cheapest SKU picked automatically, and you need active consolidation to cut costs.
Comparison with similar practices
| AKS Cluster Autoscaler | NAP (Karpenter) | VMSS autoscaling (prohibited for AKS) | |
|---|---|---|---|
| Trigger | Unschedulable pods / low requests utilization | Unschedulable Pod / consolidation / drift | VM metrics (CPU%) |
| Decision unit | Node pool (VMSS) | Individual NodeClaim (VM) | VMSS |
| Chooses size | No, only the pool's size can be used | Chooses from SKUs that meet the requirements | No |
| Understands pod constraints | Yes (simulated scheduling) | Yes | No |
Architecture diagram: where CA sits in AKS
Flowchart: the gates a node must pass before it can be scaled down
Interactive simulator: CA scale-up and scale-down timing
Adjust the profile parameters, then "advance time." The simulator runs one CA loop per scan-interval. When load rises, Pending pods trigger a scale-up. When load falls, a node is removed once its utilization stays below the threshold for unneeded-time. Select "PDB blocks" to see scale-down get stuck.
Core commands and parameters
| Command | Purpose | Key parameters |
|---|---|---|
az aks nodepool update --enable-cluster-autoscaler | Enable CA for a pool | --min-count --max-count |
az aks nodepool update --update-cluster-autoscaler | Change min/max | Can be changed at any time |
az aks nodepool update --disable-cluster-autoscaler | Disable (does not delete nodes) | Afterwards, you can use az aks nodepool scale |
az aks update --cluster-autoscaler-profile | Set cluster-wide profile | k=v,k=v; "" resets to defaults |
kubectl get cm -n kube-system cluster-autoscaler-status | CA health and per-pool status | -o yaml |
kubectl get events --field-selector source=cluster-autoscaler | CA events | reason=NotTriggerScaleUp, type=Warning |
# Enable or change CA for userpool az aks nodepool update -g $RG --cluster-name $CLUSTER -n userpool \ --update-cluster-autoscaler --min-count 3 --max-count 9 # Cluster-wide profile: suited to workloads that surge every 15 minutes az aks update -g $RG -n $CLUSTER \ --cluster-autoscaler-profile scale-down-unneeded-time=15m,scale-down-delay-after-add=15m,expander=least-waste,balance-similar-node-groups=true az aks show -g $RG -n $CLUSTER --query autoScalerProfile -o jsonc
{
"balanceSimilarNodeGroups": "true",
"expander": "least-waste",
"maxGracefulTerminationSec": "600",
"scaleDownDelayAfterAdd": "15m",
"scaleDownUnneededTime": "15m",
"scaleDownUtilizationThreshold": "0.5",
"scanInterval": "10s",
"skipNodesWithSystemPods": "true",
...
}
How to verify: the corresponding fields in autoScalerProfile have changed, and all CA-enabled pools immediately use the new profile. Common errors: writing parameter names in camelCase (the CLI uses hyphens, e.g. scale-down-unneeded-time), and leaving out time units. Production use: put the profile into IaC (the Terraform auto_scaler_profile block, hour 5).
Two official reference profiles
# Aggressive scale-down (good for saving money quickly after short batch jobs; not for clusters that fluctuate often) az aks update -g $RG -n $CLUSTER --cluster-autoscaler-profile \ scan-interval=30s,scale-down-delay-after-add=0m,scale-down-delay-after-failure=1m,scale-down-unneeded-time=3m,scale-down-unready-time=3m,max-graceful-termination-sec=30,skip-nodes-with-local-storage=false,max-empty-bulk-delete=1000,max-total-unready-percentage=100,ok-total-unready-count=1000,max-node-provision-time=15m # Bursty workloads (keep spare capacity for 10 minutes) az aks update -g $RG -n $CLUSTER --cluster-autoscaler-profile \ scan-interval=20s,scale-down-delay-after-add=10m,scale-down-delay-after-failure=1m,scale-down-unneeded-time=5m,scale-down-unready-time=5m,max-graceful-termination-sec=30,skip-nodes-with-local-storage=false,max-empty-bulk-delete=100,max-total-unready-percentage=100,ok-total-unready-count=1000,max-node-provision-time=15m # Restore defaults az aks update -g $RG -n $CLUSTER --cluster-autoscaler-profile ""
max-graceful-termination-sec=30 makes CA stop waiting for pods to exit gracefully after 30 seconds. If your myapp sets terminationGracePeriodSeconds to 60 seconds, don't copy this value.Diagnostic commands
kubectl get cm -n kube-system cluster-autoscaler-status -o yaml | sed -n '/status:/,$p' kubectl get events -A --field-selector source=cluster-autoscaler --sort-by=.lastTimestamp | tail -20 kubectl get events -A --field-selector reason=NotTriggerScaleUp # Why a node isn't scaling down: check its events and annotations kubectl describe node NODE | grep -iE "ScaleDown|cluster-autoscaler"
status: |
time: 2026-11-15 10:12:31 +0000 UTC
autoscalerStatus: Running
clusterWide:
health:
status: Healthy
nodeCounts: { registered: { total: 5, ready: 5 }, longUnregistered: 0, unregistered: 0 }
scaleUp: { status: NoActivity }
scaleDown: { status: CandidatesPresent }
nodeGroups:
- name: aks-userpool-27182818-vmss
health: { status: Healthy, nodeCounts: { registered: { total: 3, ready: 3 } }, cloudProviderTarget: 3, minSize: 3, maxSize: 9 }
The exact format of this ConfigMap changes between CA versions (newer versions use YAML, older versions use plain text), so use your cluster's actual output as the reference. To get control plane logs, enable the cluster-autoscaler category in diagnostic settings, then query AKSControlPlane | where Category == "cluster-autoscaler" in Log Analytics (resource-specific mode).
Lab 2: Trigger a scale-up with a load test, then observe the scale-down (about 25 min; up to +6 D4s_v5 ≈ +1.2 USD/hour, example estimate)
az aks nodepool show -g $RG --cluster-name $CLUSTER -n userpool --query "{auto:enableAutoScaling,min:minCount,max:maxCount,count:count}" -o tablekubectl -n myapp scale deploy/myapp --replicas=30 kubectl -n myapp get pod --field-selector=status.phase=Pending | head kubectl -n myapp describe pod $(kubectl -n myapp get pod --field-selector=status.phase=Pending -o name | head -1 | cut -d/ -f2) | sed -n '/Events/,$p'
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning FailedScheduling 20s default-scheduler 0/5 nodes are available: 2 node(s) didn't match Pod's node affinity/selector, 3 Insufficient cpu. preemption: 0/5 nodes are available: ...
Normal TriggeredScaleUp 15s cluster-autoscaler pod triggered scale-up: [{aks-userpool-27182818-vmss 3->5 (max: 9)}]kubectl get nodes -l agentpool=userpool -L topology.kubernetes.io/zone -w
az vmss list -g $(az aks show -g $RG -n $CLUSTER --query nodeResourceGroup -o tsv) --query "[].{name:name,capacity:sku.capacity}" -o table
Verify: the VMSS capacity matches the node count, and all Pending pods have changed to Running.
az aks update -g $RG -n $CLUSTER --cluster-autoscaler-profile scale-down-unneeded-time=3m,scale-down-delay-after-add=2m kubectl -n myapp scale deploy/myapp --replicas=3 kubectl get events -A --field-selector source=cluster-autoscaler -w
kube-system Normal ScaleDown node/aks-userpool-27182818-vmss000004 marked the node as toBeDeleted/unschedulable kube-system Normal ScaleDown node/aks-userpool-27182818-vmss000003 marked the node as toBeDeleted/unschedulable
kubectl annotate node NODE cluster-autoscaler.kubernetes.io/scale-down-disabled=true # Remove the annotation after the lab kubectl annotate node NODE cluster-autoscaler.kubernetes.io/scale-down-disabled-
az aks update -g $RG -n $CLUSTER --cluster-autoscaler-profile ""; keep myapp at 3 replicas.Case 1: a batch job every 15 minutes makes nodes scale up, down, and up again
Problem: the default 10-minute unneeded-time removes a node just before the next batch wave triggers a scale-up again. Each scale-up waits about 3 minutes for a VM to boot, so the task SLA is missed. Fix: scale-down-unneeded-time=20m and scale-down-delay-after-add=20m. Limitation: the profile is cluster-wide, so other pools also scale down more slowly. Moving batch work to NAP or to a separate cluster avoids this interaction.
Case 2: a StatefulSet with zone-LRS disks stays Pending forever
Problem: the zone-spanning pool scales up at random into zone 2, but the pod's PV is in zone 1 (volume node affinity), so the new node cannot be used. Fix: follow the official guidance and switch to one pool per zone (zone-aligned) with balance-similar-node-groups=true, so CA scales up the pool in zone 1. Or switch to ZRS disks (from 1.29 onward, the default managed-csi uses ZRS). Limitation: one pool per zone means more pools, so watch the 100-pool limit and the management overhead.
Case 3: scale-down stuck for two weeks, cost doubled
Problem: a team wrote its PDB as minAvailable: 100% (or maxUnavailable: 0). CA can never evict those pods, so the nodes never scale down. Fix: use kubectl get pdb -A to find PDBs with ALLOWED DISRUPTIONS of 0, and change them to maxUnavailable: 1. Add this check to the review in Module 8. Limitation: a PDB on a single-replica service always blocks, so either add replicas or accept brief downtime.
Common errors and fixes
NotTriggerScaleUp: pod didn't trigger scale-up: 1 max node group size reached
Cause: every pool that can fit this pod has already reached max-count.
az aks nodepool list -g $RG --cluster-name $CLUSTER --query "[].{n:name,count:count,max:maxCount}" -o table
Fix: raise the limit with --update-cluster-autoscaler --max-count, and check the vCPU quota and subnet IPs.
NotTriggerScaleUp: pod didn't trigger scale-up: 2 node(s) had untolerated taint {sku: gpu}, 1 Insufficient memory
Cause: CA simulates with template nodes and finds that some pools have taints and others are too small for the pod (the pod's memory requests are larger than a single node's allocatable, so adding more nodes will not help).
kubectl get pod POD -o jsonpath='{.spec.containers[*].resources.requests}'
kubectl get nodes -o custom-columns=NAME:.metadata.name,MEM:.status.allocatable.memory
Fix: lower the requests, create a pool with a larger SKU (such as the E series), or use NAP to select the SKU automatically.
Node utilization stays very low but the node is not scaled down (no ScaleDown event)
Cause: common causes include a PDB that allows 0 disruptions, non-DaemonSet pods in kube-system, bare pods, the safe-to-evict: "false" annotation, the pool already at min-count, or DaemonSet requests that keep utilization at or above the threshold.
kubectl get pdb -A
kubectl get pod -A -o wide --field-selector spec.nodeName=NODE
kubectl get pod -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name} {.metadata.annotations.cluster-autoscaler\.kubernetes\.io/safe-to-evict}{"\n"}{end}' | grep false
Fix: correct the PDB; add PDBs for the movable components in kube-system; set ignore-daemonsets-utilization=true if needed.
Failed to scale up: … OverconstrainedZonalAllocationRequest / ZonalAllocationFailed
Cause: the zone has insufficient capacity for this SKU, so after max-node-provision-time, CA marks that pool as in backoff.
kubectl get cm -n kube-system cluster-autoscaler-status -o yaml | grep -iA3 backoff
Fix: prepare a second pool with a similar SKU as a fallback (the expander will choose the other pool), or use NAP's multi-SKU selection; use capacity reservations for critical capacity.
CA stops working completely: cluster-autoscaler-status shows health Unhealthy (too many unready nodes)
Cause: the number of unready nodes exceeds max-total-unready-percentage (45%) and is greater than ok-total-unready-count (3), so CA enters a protected state and stops acting.
Fix: fix the NotReady nodes first (network, image, or disk pressure; see hour 7), then watch CA recover. Do not blindly raise these two thresholds.
1. Change the cluster's scale-down rule so a node is removed only after it has been unneeded for 20 minutes, and use the least-waste expander to choose a node pool.
az aks update -g $RG -n $CLUSTER --cluster-autoscaler-profile scale-down-unneeded-time=20m,expander=least-waste
2. List all recent events where scale-up was not triggered.
kubectl get events -A --field-selector source=cluster-autoscaler,reason=NotTriggerScaleUp --sort-by=.lastTimestamp
Node CPU utilization is actually 95% and the app is slow, but CA does not scale up. What are the likely causes and fixes?
CA only scales up for pods that cannot be scheduled because of insufficient resources. All existing pods are already scheduled, and their requests are far below actual usage (heavy overcommitment), so there are no Pending pods. Fix: set requests close to real usage (or use VPA recommendations), and configure an HPA to scale on CPU utilization. New replicas only become Pending when they don't fit, which then triggers CA.
Verified instructional videos
Official documentation
Video storyboard script (about 90 seconds)
This course file cannot generate a video or MP3 directly. A storyboard and narration script are provided, which you can hand to a video tool.
Visual: three nodes are full of pods, and a new pod is stuck outside with the label Pending Insufficient cpu.
Narration: the cluster autoscaler checks every ten seconds for pods that cannot be scheduled because of insufficient resources.
Visual: CA uses a dashed-line node template to test-fit the pod against two node pools, selects userpool, and the VMSS capacity changes from 3 to 5.
Narration: it simulates scheduling with each node pool's template, picks a pool that can fit the pod, and then adds instances to the scale set through the Azure API.
Visual: load drops, and one node's utilization bar falls below the 50% dashed line. A timer runs from 0 to 10 minutes, then the node is tainted, its pods are evicted, and the node disappears.
Narration: utilization is calculated from requests. A node is deleted only when it stays below half for ten minutes and all of its pods can be moved elsewhere.
Visual: a PDB shield blocks the eviction, and the timer resets to zero.
Narration: PDBs, system pods, and the scale-down-disabled annotation all keep a node in place.
Module 3 · Node Auto Provisioning (NAP / Karpenter)
- Explain how NAP relates to Karpenter (AKS runs the open-source Karpenter as a managed deployment, using karpenter-provider-azure), and the three objects:
NodePool,AKSNodeClass, andNodeClaim. - Write a NodePool with SKU selectors (
karpenter.azure.com/sku-family,sku-cpu,karpenter.sh/capacity-type, and so on),limits, andweight. Write an AKSNodeClass withimageFamily,osDiskSizeGB, andmaxPods. - Understand consolidation (
WhenEmpty/WhenEmptyOrUnderutilized), drift, expiration, disruption budgets, andkarpenter.sh/do-not-disrupt, and remember NAP's network requirements and limitations. - Use the core animation to compare how Cluster Autoscaler and NAP each decide on the same Pending pod.
What: what NAP is
NAP is the managed Karpenter in AKS. Based on a Pending pod's resource needs and scheduling constraints, it decides on and creates the most suitable VM configuration directly, instead of adding instances to a VMSS with a fixed SKU. AKS Automatic clusters enable NAP by default. On AKS Standard clusters, enable it with --node-provisioning-mode Auto (the default is Manual). The NAP controller runs in the managed control plane, and AKS manages its version (for example, the component table lists karpenter 1.12.2-aks for 1.36 and 1.7.0-aks for 1.35).
| Object | API | Who maintains it | Purpose |
|---|---|---|---|
NodePool | karpenter.sh/v1 | You (NAP creates default and system-surge by default) | Constraints: allowed SKUs, capacity types, zones, and architectures; taints and labels; limits, weight, and disruption policy |
AKSNodeClass | karpenter.azure.com/v1beta1 | You (default by default) | Azure-side settings: imageFamily (Ubuntu / AzureLinux / AzureContainerLinux), osDiskSizeGB (default 128, minimum 30), maxPods, vnetSubnetID, kubelet, GPU, and tags |
NodeClaim | karpenter.sh/v1 | NAP | A request for "a machine like this" and its status, which maps to one node |
Why: what it solves compared with CA
- No need to plan SKUs in advance: one NodePool can allow an entire D/E/F family, and NAP chooses based on pod needs and price.
- Fits more in one step: Karpenter combines Pending pods that arrive close together and picks the instance combination that fits them all (bin packing).
- Active cost reduction: consolidation deletes empty nodes, or replaces several underutilized nodes with one cheaper node. CA only deletes; it does not swap for a smaller node.
- Declarative rolling updates: changing AKSNodeClass (such as imageFamily or the subnet) triggers drift, and NAP replaces nodes step by step within the budget.
How: the real path of a NAP scale-up
- kube-scheduler cannot schedule the pod, so it sets
PodScheduled=False / Unschedulable. - Karpenter's provisioner sees the Pending pod and collects pods that arrive together within a short batching window.
- For each NodePool (skipping pools whose taints the pod does not tolerate), it computes NodePool requirements ∩ the pod's nodeSelector/nodeAffinity/topology constraints to get the candidate SKU set. If several pools match, it uses the one with the highest
weight. - It chooses the instance type based on resource requests (including an estimate of DaemonSet overhead; the default pool adds the
kubernetes.azure.com/ebpf-dataplane: ciliumlabel precisely so the overhead can be predicted) and on price. When both Spot and On-demand are allowed, it prefers Spot. - It creates a
NodeClaim, and the Azure provider uses it to create the VM in the node resource group (NIC and disk; a temporary OS disk is used automatically when possible). The node gets thekarpenter.sh/nodepoollabel and a startup taint (Cilium'snode.cilium.io/agent-not-ready). - After the kubelet registers and the CNI is ready, the startup taint is removed, and kube-scheduler binds the pod.
Disruption mechanisms
| Method | Type | Configuration | Limited by NodePool budgets? |
|---|---|---|---|
| Consolidation | Automatic, graceful | spec.disruption.consolidationPolicy: WhenEmpty | WhenEmptyOrUnderutilized, consolidateAfter (can be set to Never) | Yes |
| Drift | Automatic, graceful | Changing the NodePool template or AKSNodeClass (tags are the exception) | Yes |
| Expiration | Automatic, forced | expireAfter (Never for the default pool) | No (but PDBs are still respected when evicting pods) |
| Manual | Forced | kubectl delete node / nodeclaim / nodepool | No |
If no budgets are set, Karpenter defaults to nodes: 10%; the default NodePool is set to 30%. A schedule (UTC cron) plus a duration can define a maintenance window. Once terminationGracePeriod expires, it bypasses PDBs and do-not-disrupt. The pod or node annotation karpenter.sh/do-not-disrupt: "true" only blocks consolidation and drift.
Network requirements and limitations (verified 2026-11)
| Item | NAP support |
|---|---|
| Azure CNI Overlay | Supported (recommended, with the Cilium dataplane) |
| Azure CNI Node Subnet | Supported |
| Azure CNI Pod Subnet (dynamic IP allocation) | Not supported |
| kubenet / Calico network policy | Not supported |
| IPv6 single-stack | Not supported (dual-stack is in preview) |
- Windows node pools are outside NAP's official support scope (the
Windows2022/2025image families in AKSNodeClass are in preview and do not support the Cilium dataplane). - Service principals are not supported; only system or user-assigned managed identities can be used. Clusters with NAP enabled cannot run
az aks stop. The outbound type cannot be changed after creation. A custom VNet must use a Standard LB. Azure CLI ≥ 2.76.0. - Coexistence with CA: the official limitations list does not treat them as conflicting, but both react to Pending pods. The conservative approach is to send business pods to only one of them: either a NAP NodePool or a VMSS pool with CA enabled, separated with taints and labels (follow the official documentation).
When: selection guidance (official)
| Scenario | Recommendation |
|---|---|
| Most new production workloads | AKS Automatic (NAP preconfigured, with an SLA for pod readiness) |
| Needs fine-grained platform customization | AKS Standard + NAP |
| Windows, kubenet, the need to stop the cluster, or a fixed VMSS operations model | AKS Standard + CA |
Comparison with similar practices
| AKS NAP | Self-managed Karpenter (Azure provider) | EKS Karpenter | |
|---|---|---|---|
| Where it runs | Managed control plane, upgraded by AKS | Installed in the cluster with Helm, upgraded by you | In the cluster (managed in EKS Auto Mode) |
| Node class | AKSNodeClass | AKSNodeClass | EC2NodeClass |
| Supported | Microsoft support | Community | AWS |
az aks nodepool scale": NAP nodes do not belong to an AKS agent pool. Control them with the NodePool's limits/replicas (static pool). ② "Disruption budgets block expiration": they don't. Expiration is a forced method. ③ "Changing AKSNodeClass modifies nodes in place": it doesn't. It triggers drift and replaces nodes (except for tags). ④ "NAP ignores PDBs": it respects PDBs during eviction, unless terminationGracePeriod expires.Architecture diagram: object relationships in NAP
Flowchart: how CA and NAP decisions differ
Core animation: how a Pending pod triggers scale-up decisions in Cluster Autoscaler and NAP
Choose a scenario, then play it step by step. On the left is a cluster with CA enabled (node pools: userpool D4s_v5 max 9, spotpool D8as_v5 with a Spot taint). On the right is a cluster with NAP enabled (NodePool default: sku-family D, on-demand; NodePool batch: D/E/F, spot + on-demand, with the workload=batch:NoSchedule taint). The terminal below shows the corresponding API calls, events, and objects.
The price ordering and timing in the animation are illustrative and explain the mechanism. Real selection depends on the SKUs available in the region, quotas, Spot capacity, and the Karpenter version.
Core commands and parameters
| Command | Purpose | Key parameters |
|---|---|---|
az aks create --node-provisioning-mode Auto | Create a new cluster with NAP enabled | --network-plugin azure --network-plugin-mode overlay --network-dataplane cilium |
az aks update --node-provisioning-mode Auto | Enable on an existing cluster | --node-provisioning-default-pools Auto|None |
az aks update --node-provisioning-mode Manual | Disable (drain NAP nodes first) | See the steps below |
kubectl get nodepools,aksnodeclasses,nodeclaims | View NAP objects | -o wide, describe |
kubectl get events --field-selector source=karpenter-events | NAP events | Control plane log category node-auto-provisioning |
kubectl get nodes -l karpenter.sh/nodepool | List NAP nodes | -L karpenter.sh/capacity-type,node.kubernetes.io/instance-type |
Create a NAP lab cluster
NAP_CLUSTER=aks-lab-nap az aks create -g $RG -n $NAP_CLUSTER -l $LOC --tier standard \ --kubernetes-version 1.36 \ --node-provisioning-mode Auto \ --network-plugin azure --network-plugin-mode overlay --network-dataplane cilium \ --pod-cidr 192.168.0.0/16 \ --node-count 2 --node-vm-size Standard_D4s_v5 \ --generate-ssh-keys az aks get-credentials -g $RG -n $NAP_CLUSTER --overwrite-existing kubectl get nodepools,aksnodeclasses
NAME NODECLASS NODES READY AGE nodepool.karpenter.sh/default default 0 True 6m nodepool.karpenter.sh/system-surge default 0 True 6m NAME READY AGE aksnodeclass.karpenter.azure.com/default True 6m
View the default NodePool
kubectl get nodepool default -o yaml | sed -n '/^spec:/,/^status:/p'
spec:
disruption:
consolidateAfter: 0s
budgets:
- nodes: "30%"
template:
metadata:
labels:
kubernetes.azure.com/mode: user
kubernetes.azure.com/ebpf-dataplane: cilium
spec:
expireAfter: Never
requirements:
- { key: kubernetes.io/arch, operator: In, values: ["amd64"] }
- { key: kubernetes.io/os, operator: In, values: ["linux"] }
- { key: karpenter.sh/capacity-type, operator: In, values: ["on-demand"] }
- { key: karpenter.azure.com/sku-family, operator: In, values: ["D"] }
startupTaints:
- { key: node.cilium.io/agent-not-ready, effect: NoExecute, value: "true" }
nodeClassRef: { group: karpenter.azure.com, kind: AKSNodeClass, name: default }
Custom: batch NodePool + Azure Linux node class
apiVersion: karpenter.azure.com/v1beta1
kind: AKSNodeClass
metadata:
name: azl
spec:
imageFamily: AzureLinux
osDiskSizeGB: 64
maxPods: 110
tags:
CostCenter: "aks-lab"
---
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: batch
spec:
weight: 10
limits:
cpu: "64"
memory: 256Gi
disruption:
consolidationPolicy: WhenEmptyOrUnderutilized
consolidateAfter: 1m
budgets:
- nodes: "20%"
- nodes: "0"
schedule: "0 13 * * 1-5" # UTC, Monday to Friday from 13:00, no voluntary disruption for 8 hours
duration: 8h
template:
metadata:
labels: { workload: batch }
spec:
expireAfter: 720h
taints:
- { key: workload, value: batch, effect: NoSchedule }
requirements:
- { key: karpenter.sh/capacity-type, operator: In, values: ["spot", "on-demand"] }
- { key: karpenter.azure.com/sku-family, operator: In, values: ["D", "E", "F"] }
- { key: karpenter.azure.com/sku-cpu, operator: Lt, values: ["17"] }
- { key: kubernetes.io/arch, operator: In, values: ["amd64"] }
- { key: topology.kubernetes.io/zone, operator: In, values: ["canadacentral-1", "canadacentral-2", "canadacentral-3"] }
nodeClassRef: { group: karpenter.azure.com, kind: AKSNodeClass, name: azl }
kubectl apply -f nap-batch.yaml
kubectl get nodepool batch -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}{"\n"}'
Note: NodePools should be mutually exclusive (each pod matches only one pool). If several match, the one with the highest weight is used. The official documentation notes that consolidateAfter "can currently only be set with WhenEmpty", but the default pool and the managed GPU example set it under WhenEmptyOrUnderutilized. If apply returns a validation error, remove that field (your cluster's CRD validation is the authority). expireAfter sits under spec.template.spec in karpenter.sh/v1 (consistent with the default pool).
Disable NAP (summary of the official steps)
# 1) Set spec.limits.cpu: 0 on all NodePools (prevents new nodes)
kubectl patch nodepool default --type merge -p '{"spec":{"limits":{"cpu":"0"}}}'
# 2) Add the karpenter.azure.com/disable:NoSchedule taint to all NodePools to trigger migration (PDBs are respected)
# 3) Scale up the fixed AgentPool to take the workload; 4) Confirm there are no NAP nodes
kubectl get nodes -l karpenter.sh/nodepool
# 5) Switch back to Manual
az aks update -g $RG -n $NAP_CLUSTER --node-provisioning-mode Manual
Lab 3: observe NAP SKU selection, Spot preference, and consolidation on aks-lab-nap (about 25 minutes)
apiVersion: batch/v1
kind: Job
metadata: { name: crunch }
spec:
parallelism: 6
completions: 6
template:
spec:
restartPolicy: Never
nodeSelector: { workload: batch }
tolerations:
- { key: workload, operator: Equal, value: batch, effect: NoSchedule }
containers:
- name: crunch
image: mcr.microsoft.com/azurelinux/base/core:3.0
command: ["sh", "-c", "sleep 300"]
resources: { requests: { cpu: "1500m", memory: 3Gi } }
kubectl apply -f batch-job.yaml kubectl get nodeclaims -w
NAME TYPE CAPACITY ZONE NODE READY AGE batch-7xk2q Standard_D8as_v5 spot canadacentral-2 Unknown 8s batch-7xk2q Standard_D8as_v5 spot canadacentral-2 aks-batch-7xk2q True 94s
6 × 1.5 cores = 9 cores of requests: NAP may choose one 16-core node or two 8-core nodes (depending on price and Spot capacity). CAPACITY showing spot reflects the rule that Spot is preferred when both are allowed.
kubectl get nodes -l karpenter.sh/nodepool=batch -L node.kubernetes.io/instance-type,karpenter.sh/capacity-type,topology.kubernetes.io/zone,kubernetes.azure.com/os-sku kubectl get events -A --field-selector source=karpenter-events --sort-by=.lastTimestamp | tail
consolidateAfter: 1m:
kubectl get nodeclaims -w kubectl describe nodeclaim NAME | sed -n '/Events/,$p'
Normal DisruptionTerminating nodeclaim/batch-7xk2q Disrupting NodeClaim: Empty Normal Finalized nodeclaim/batch-7xk2q Finalized karpenter.sh/termination
osDiskSizeGB in AKSNodeClass to 80, then submit another Job. Any old node still running will be marked Drifted and replaced: kubectl get nodeclaims -o custom-columns='NAME:.metadata.name,DRIFTED:.status.conditions[?(@.type=="Drifted")].status'kubectl delete job crunch; az aks delete -g $RG -n $NAP_CLUSTER --yes --no-wait (deleting the cluster also deletes the VMs that NAP created).Case 1: replace 7 fixed-SKU node pools with NAP
Problem: the platform team maintained 7 CA node pools (D4/D8/E8/F16, and so on) for different teams. They were badly fragmented, with average requests utilization of 38%. Fix: move to NAP with one general-purpose NodePool (D/E families, on-demand) and one batch NodePool (Spot preferred, with a taint), and enable WhenEmptyOrUnderutilized. Configuration: budget 10% plus nodes: "0" during working hours; add PDBs to critical services. Limitation: consolidation moves pods, so services with a single replica or slow startup need protection through karpenter.sh/do-not-disrupt or adjusted budgets.
Case 2: changing the AKSNodeClass subnet replaced 30% of nodes in one afternoon
Problem: an operator changed vnetSubnetID to prepare for using a new subnet later. That triggered drift, and all related nodes were replaced under the default 30% budget. Fix: create a new AKSNodeClass and NodePool, then migrate step by step. Set conservative budgets on production NodePools (nodes: "1"). Limitation: before using the new subnet, grant the cluster identity subnet read/join permissions and make sure there are enough IPs.
Case 3: an unexpectedly large SKU
Problem: a pod with a mistyped requests.memory: 200Gi made NAP buy a large-memory M-series machine. Fix: add karpenter.azure.com/sku-cpu Lt 17, sku-family In [D,E], and limits to the NodePool, and add a LimitRange/ResourceQuota in the namespace. Limitation: limits are a total cap per NodePool. Once reached, pods stay Pending (the events will say so).
Common errors and fixes
Pod Pending, karpenter event: incompatible with nodepool "default", ... did not tolerate taint / no instance type satisfied resources and requirements
Cause: the pod's constraints do not intersect with the requirements of any NodePool (for example, it requires arm64 but the pool only allows amd64, or the requested memory exceeds the largest allowed SKU), or the pod does not tolerate the pool's taints.
kubectl get events -A --field-selector source=karpenter-events --sort-by=.lastTimestamp | tail kubectl get nodepools -o yaml | grep -A20 requirements
Fix: adjust the pod's nodeSelector/tolerations, or relax the NodePool's SKU selectors. Note that the exact event text depends on the Karpenter version.
NodeClaim stays Launched=False / node never becomes Ready (quota or capacity shortage)
Cause: insufficient subscription vCPU quota, insufficient Spot capacity, the SKU is not available in the zone, or a custom subnet lacks join permission or has run out of IPs.
kubectl describe nodeclaim NAME | sed -n '/Conditions/,$p' az vm list-usage -l $LOC -o table | grep -i family
Fix: request more quota; relax the SKU family so NAP has more choices; grant the cluster identity subnet read + join/action.
(OperationNotAllowed) Cannot stop the cluster: az aks stop fails on a cluster with NAP enabled
Cause: official limitation: clusters with NAP enabled cannot be stopped.
Fix: delete lab clusters as soon as you finish with them. For environments that need to be shut down overnight, use CA node pools and az aks stop, or set the NodePool limits to 0 and delete the NAP nodes.
NodePool at its limit: all available instance types exceed limits for nodepool
Cause: the NodePool's spec.limits (total cpu/memory) is used up.
kubectl get nodepool batch -o jsonpath='{.spec.limits}{"\n"}{.status.resources}{"\n"}'
Fix: raise the limits, or let consolidation reclaim idle capacity first.
Nodes are replaced frequently (consolidation churn), and apps keep restarting
Cause: WhenEmptyOrUnderutilized combined with loose budgets, so NAP keeps swapping nodes for smaller ones as the load fluctuates.
Fix: tighten the budgets (nodes: "1", or 0 during working hours), set karpenter.sh/do-not-disrupt: "true" on critical pods, configure PDBs for the services, and change latency-sensitive pools to WhenEmpty.
1. Enable NAP on an existing cluster without creating the default NodePool.
az aks update -g $RG -n $CLUSTER --node-provisioning-mode Auto --node-provisioning-default-pools None
Prerequisite: the cluster networking meets NAP requirements (Overlay or Node Subnet, not kubenet or Calico).
2. List the SKU, capacity type, and availability zone for all NAP nodes.
kubectl get nodes -l karpenter.sh/nodepool -L karpenter.sh/nodepool,node.kubernetes.io/instance-type,karpenter.sh/capacity-type,topology.kubernetes.io/zone
A pod requests 2 CPU / 24Gi memory, and the cluster only has a CA node pool of D4s_v5 (max not yet reached). What will CA and NAP each do?
CA simulates with a template node: D4s_v5 allocatable memory is about 12–13.5 GiB, which is not enough for 24Gi, so CA does not scale up, and the event is NotTriggerScaleUp (Insufficient memory). NAP (whose NodePool allows the D/E families) intersects the requirements to get SKUs with at least 24Gi allocatable (such as E4as_v5 with 32 GiB or D8as_v5 with 32 GiB), selects by price, creates a NodeClaim, and the pod runs on the new node. The CA fix is to create a node pool with more memory.
Verified instructional videos
Official documentation
- Overview of node auto-provisioning
- Enable or disable NAP
- Configure NodePools
- Configure AKSNodeClass
- Disruption policies
- Networking for NAP
- Karpenter Concepts (upstream)
Video storyboard (about 100 seconds)
This course file cannot generate a video or MP3 directly. A storyboard and narration script are provided, which you can hand to a video tool.
Visual: split screen, with the same Pending pod (24Gi) appearing in both the CA cluster and the NAP cluster.
Narration: the same pod, handed to the cluster autoscaler or to node auto-provisioning, can produce completely different results.
Visual: on the left, CA tries the D4s_v5 template and fails, with a red cross and the NotTriggerScaleUp event.
Narration: the cluster autoscaler can only scale up existing node pools. If the pool's SKU is too small, it can do nothing.
Visual: on the right, Karpenter intersects the NodePool requirements with the pod's requirements, the SKU list is filtered and sorted by price, a NodeClaim is generated, and an E4as_v5 appears.
Narration: node auto-provisioning intersects the node pool's constraints with the pod's needs, then picks the most suitable machine among the SKUs that qualify.
Visual: the load ends, and the empty node disappears after consolidateAfter. A budget table shows that at most 20% can be disrupted at the same time.
Narration: once the load drops, it also consolidates nodes, deleting idle machines or replacing them with cheaper ones. The pace is controlled by the disruption budget.
Module 4 · Pod scaling: HPA, the KEDA add-on, and VPA
- Calculate the HPA's desired replicas (
ceil(current replicas × current metric / target)), and usebehaviorto control the scaling speed and stabilization windows. - Install the KEDA add-on with
--enable-keda, write aScaledObject(Redis list, cron, Azure Service Bus) and aTriggerAuthentication(Workload Identity), and understand that 0↔1 is activated by the KEDA operator, while 1↔N is handled by the HPA it generates. - Install VPA with
--enable-vpa, choose amongOff / Initial / Recreate / InPlaceOrRecreate, and avoid conflicts with HPA on the same metric.
What: three types of pod scalers
| HPA | KEDA (AKS add-on) | VPA (AKS add-on) | |
|---|---|---|---|
| What it changes | Replica count | Replica count (including scale-to-zero) | Container requests (and limits, proportionally) |
| Based on | Resource metrics (metrics-server), custom/external metrics | 70+ event source scalers: queue length, cron, Prometheus, Kafka lag, and more | Historical CPU/memory usage and OOM events |
| AKS installation | Built in (metrics-server is managed by AKS) | az aks update --enable-keda | az aks update --enable-vpa |
| Version | Follows K8s | Pinned minor version per K8s release: 1.35 → 2.17, 1.36 → 2.19, 1.37 → 2.20 | 1.35 → 1.5.1, 1.36 → 1.6.0, 1.37 → 1.7.1 |
Why: how pod scaling and node scaling chain together
HPA/KEDA adds replicas → nodes don't have room → pods go Pending → CA/NAP adds nodes (2–4 minutes) → pods run. So end-to-end scale-up latency = metric collection (metrics-server, about 15–60 seconds) + HPA sync period (15 seconds by default) + node boot time. For sudden traffic, either leave headroom (a lower target utilization or a higher minReplicas), or use a KEDA cron to scale up in advance.
How: key mechanics
HPA
- Desired replicas =
ceil(currentReplicas × currentMetricValue / desiredMetricValue). No adjustment is made if the difference from the target is within the 10% tolerance. With multiple metrics, the largest result is used. - CPU utilization = usage / requests. A container without requests has no computable utilization.
- The default scale-down stabilization window is 300 seconds.
spec.behavior.scaleUp/scaleDown.policiescan limit how many replicas (or what percentage) can be added or removed in each period.
KEDA
- The add-on deploys
keda-operator,keda-operator-metrics-apiserver(which implementsexternal.metrics.k8s.io), andkeda-admission-webhooksin kube-system, with 2 replicas each. - You create a
ScaledObject(keda.sh/v1alpha1), and KEDA generates an HPA namedkeda-hpa-<name>for it. Activation and deactivation between 0 and 1 replicas is handled by the operator, usingpollingInterval(default 30 seconds) andcooldownPeriod(default 300 seconds). For batch work, useScaledJob. - Authentication uses
TriggerAuthentication;podIdentity.provider: azure-workload(Workload Identity, hour 3) is recommended. KEDA 2.15+ has removed the old pod identity. - Add-on limitations: you cannot change the resources of the KEDA operator/metrics server or other Helm values. If you need customization, you can only install KEDA yourself (not supported by Azure). If keda-operator is OOMKilled, the official recommendation is to use VPA (
InPlaceOrRecreate) to adjust it.
VPA
- Components:
vpa-recommender(calculates recommendations),vpa-updater(evicts or adjusts in place), andvpa-admission-controller(rewrites requests when pods are created). Since AKS 1.34, each of the three defaults to 2 replicas (high availability). updateMode:Off(recommendations only),Initial(set only at creation),Recreate(evict and recreate),InPlaceOrRecreate(AKS 1.34+; prefers in-place resize and falls back to eviction).Autohas been deprecated since VPA 1.4.0 (AKS 1.34+) and behaves the same as Recreate. If unspecified, it is treated as Recreate.controlledValues: RequestsAndLimits(default) also adjusts limits proportionally;RequestsOnlychanges only requests.
When: choosing and combining
| Scenario | Recommendation |
|---|---|
| Stateless web (myapp) | HPA (CPU 60–70%) + node CA/NAP; use VPA only in Off mode to suggest requests |
| Queue consumers, event-driven workloads, nightly scale-to-zero | KEDA (queue length / cron), can scale to 0 |
| Monoliths that are hard to scale out, JVM heap tuning | VPA (Initial or InPlaceOrRecreate) |
| Using HPA and VPA on the same workload | Only when the HPA uses custom/external metrics and VPA manages CPU/memory. Do not stack them on the same CPU/memory metric. |
Comparison with similar practices
| KEDA add-on | Self-installed KEDA (Helm) | Azure Container Apps scaling | |
|---|---|---|---|
| Upgrade | With the AKS version | Your responsibility | Built into the platform (runs KEDA underneath) |
| Customizable | Helm values cannot be changed | Fully customizable | Rule-level |
| Supported | Microsoft support (GA K8s versions) | Community | Microsoft |
InPlaceOrRecreate. ③ "The HPA's CPU target is a percentage of node CPU": it is relative to the pod's requests. ④ "Scaling to 0 has no cost": the first request or message must wait for activation, an image pull, and possibly node provisioning. An HTTP service that scales to 0 needs an extra HTTP interceptor component (the KEDA HTTP add-on is not part of the AKS add-ons).Architecture diagram: how the KEDA add-on relates to HPA and node scaling
Flowchart: end-to-end timeline of a traffic burst
Interactive simulator: HPA formula + KEDA queue scaling
Upper half: enter the current replica count and CPU utilization to see the HPA calculation. Lower half: the length of the Redis list jobs changes over time, and a ScaledObject (listLength: 5, min 0 / max 20) drives the worker replicas. When node capacity is insufficient, pods go Pending and trigger node scale-up.
Core commands and parameters
| Command | Purpose | Description |
|---|---|---|
kubectl autoscale deploy myapp --cpu-percent=60 --min=3 --max=20 | Quickly create an HPA | Production YAML (autoscaling/v2 + behavior) |
az aks update --enable-keda / --disable-keda | KEDA add-on | Verify: --query workloadAutoScalerProfile.keda.enabled |
az aks update --enable-vpa / --disable-vpa | VPA add-on | CLI ≥ 2.52.0 |
kubectl get hpa,scaledobject -n myapp | View scaling objects | READY/ACTIVE columns of the ScaledObject |
kubectl describe vpa NAME | View recommendations | Lower Bound / Target / Upper Bound |
HPA (autoscaling/v2, with behavior)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: myapp, namespace: myapp }
spec:
scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: myapp }
minReplicas: 3
maxReplicas: 30
metrics:
- type: Resource
resource: { name: cpu, target: { type: Utilization, averageUtilization: 60 } }
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- { type: Percent, value: 100, periodSeconds: 30 }
- { type: Pods, value: 6, periodSeconds: 30 }
selectPolicy: Max
scaleDown:
stabilizationWindowSeconds: 300
policies:
- { type: Percent, value: 20, periodSeconds: 60 }
KEDA add-on
az aks update -g $RG -n $CLUSTER --enable-keda
az aks show -g $RG -n $CLUSTER --query "workloadAutoScalerProfile.keda.enabled"
kubectl get pods -n kube-system | grep keda
kubectl get crd scaledobjects.keda.sh -o jsonpath='{.metadata.labels.app\.kubernetes\.io/version}{"\n"}'
true keda-admission-webhooks-7d9c8f6b5d-2n9zl 1/1 Running 0 3m keda-admission-webhooks-7d9c8f6b5d-69dkg 1/1 Running 0 3m keda-operator-6b8f4c7d9-4hb5n 1/1 Running 0 3m keda-operator-6b8f4c7d9-pckpx 1/1 Running 0 3m keda-operator-metrics-apiserver-5c6d7f8b9-gqg4s 1/1 Running 0 3m keda-operator-metrics-apiserver-5c6d7f8b9-trfcb 1/1 Running 0 3m 2.19.0
ScaledObject: scale workers based on Redis list length (can scale to 0)
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: { name: myapp-worker, namespace: myapp }
spec:
scaleTargetRef: { name: myapp-worker }
minReplicaCount: 0
maxReplicaCount: 20
pollingInterval: 15
cooldownPeriod: 120
triggers:
- type: redis
metadata:
address: redis.myapp.svc.cluster.local:6379
listName: jobs
listLength: "5" # each replica processes 5 messages
activationListLength: "0"
ScaledObject: pre-warm myapp on weekdays from 8:00 to 19:00 (Toronto time)
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: { name: myapp-cron, namespace: myapp }
spec:
scaleTargetRef: { name: myapp }
minReplicaCount: 3
maxReplicaCount: 30
triggers:
- type: cron
metadata: { timezone: America/Toronto, start: "0 8 * * 1-5", end: "0 19 * * 1-5", desiredReplicas: "8" }
- type: cpu
metricType: Utilization
metadata: { value: "60" }
Note: before using myapp-cron, you must delete the manually created myapp HPA (a Deployment can have only one HPA). A CPU trigger requires CPU requests to be set on the container. Workload Identity authentication (Service Bus example): in TriggerAuthentication, set spec.podIdentity.provider: azure-workload, and create a federated credential for the keda-operator service account (hour 3). If KEDA was enabled before Workload Identity, run kubectl rollout restart deployment keda-operator -n kube-system.
VPA add-on
az aks update -g $RG -n $CLUSTER --enable-vpa kubectl get pods -n kube-system | grep vpa kubectl get crd | grep verticalpodautoscalers
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata: { name: myapp-vpa, namespace: myapp }
spec:
targetRef: { apiVersion: apps/v1, kind: Deployment, name: myapp }
updatePolicy:
updateMode: "Off" # When used with HPA(CPU), only take the recommendations
resourcePolicy:
containerPolicies:
- containerName: myapp
minAllowed: { cpu: 100m, memory: 128Mi }
maxAllowed: { cpu: "2", memory: 2Gi }
controlledResources: ["cpu", "memory"]
kubectl apply -f myapp-vpa.yaml kubectl -n myapp describe vpa myapp-vpa | sed -n '/Recommendation/,$p'
Lab 4: myapp HPA + Redis queue-driven workers (KEDA) + VPA recommendations (about 20 minutes)
kubectl apply -f myapp-hpa.yaml kubectl -n myapp run load --image=busybox:1.37 --restart=Never -- /bin/sh -c "while true; do wget -q -O- http://myapp/ >/dev/null; done" kubectl -n myapp get hpa myapp -w
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE myapp Deployment/myapp cpu: 12%/60% 3 30 3 20s myapp Deployment/myapp cpu: 148%/60% 3 30 3 75s myapp Deployment/myapp cpu: 148%/60% 3 30 8 90s
ceil(3 × 148 / 60) = 8. To stop the load test: kubectl -n myapp delete pod load. After a stabilization window of about 5 minutes, replicas scale back down step by step.
apiVersion: apps/v1
kind: Deployment
metadata: { name: myapp-worker, namespace: myapp }
spec:
replicas: 0
selector: { matchLabels: { app: myapp-worker } }
template:
metadata: { labels: { app: myapp-worker } }
spec:
nodeSelector: { workload: general }
containers:
- name: worker
image: redis:7-alpine
command: ["sh", "-c", "while true; do redis-cli -h redis BRPOP jobs 5 >/dev/null; sleep 2; done"]
resources: { requests: { cpu: 100m, memory: 64Mi }, limits: { memory: 128Mi } }
az aks update -g $RG -n $CLUSTER --enable-keda kubectl apply -f myapp-worker.yaml -f worker-scaledobject.yaml kubectl -n myapp get scaledobject myapp-worker
NAME SCALETARGETKIND SCALETARGETNAME MIN MAX READY ACTIVE AGE myapp-worker apps/v1.Deployment myapp-worker 0 20 True False 15s
kubectl -n myapp exec deploy/redis -- sh -c 'for i in $(seq 1 60); do redis-cli LPUSH jobs job-$i >/dev/null; done; redis-cli LLEN jobs' kubectl -n myapp get hpa keda-hpa-myapp-worker -w
60 NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS keda-hpa-myapp-worker Deployment/myapp-worker 60/5 (avg) 1 20 1 keda-hpa-myapp-worker Deployment/myapp-worker 30/5 (avg) 1 20 12
After the queue is empty and cooldownPeriod (120 seconds) ends, replicas return to 0.
az aks update -g $RG -n $CLUSTER --enable-vpa
kubectl apply -f myapp-vpa.yaml
sleep 300; kubectl -n myapp get vpa myapp-vpa -o jsonpath='{.status.recommendation.containerRecommendations[0]}{"\n"}'
{"containerName":"myapp","lowerBound":{"cpu":"100m","memory":"128Mi"},"target":{"cpu":"163m","memory":"174Mi"},"uncappedTarget":{"cpu":"163m","memory":"174Mi"},"upperBound":{"cpu":"612m","memory":"420Mi"}}kubectl -n myapp delete scaledobject myapp-worker; kubectl -n myapp delete deploy myapp-worker; kubectl -n myapp delete vpa myapp-vpa. Keep the HPA for the Capstone lab. The add-ons can stay, or be removed with az aks update --disable-keda --disable-vpa.Case 1: a flood of 502 errors within 3 minutes of a promotion starting
Problem: the HPA target is 80%, and traffic suddenly rises 5×. New replicas are Pending while nodes boot, and the old replicas are overloaded. Fix: a KEDA cron raises minReplicas to 20 thirty minutes before the event, the HPA target is lowered to 60%, and CA uses scale-down-delay-after-add=30m. Limitation: pre-warming needs budget; node boot time depends on image size, so it can be combined with Artifact Streaming (Premium ACR).
Case 2: a Service Bus consumer scales to 0 overnight and frees up a whole node pool
Problem: the order reconciliation service runs 20 replicas during the day and has almost no messages at night. Fix: KEDA azure-servicebus scaler + Workload Identity, with minReplicaCount 0; CA min 0 on the Spot pool where it runs. Limitation: the delay for the first message = polling interval + node boot + image pull, about 3–5 minutes, so the business must accept this.
Case 3: VPA and HPA fight, and the replica count oscillates
Problem: the same Deployment has both HPA(CPU 60%) and VPA(Recreate, controlling CPU). VPA raises requests → utilization drops → HPA scales in → utilization rises → VPA adjusts again… Fix: set VPA to Off so it only produces recommendations, and let the release process update requests periodically; or let VPA control only memory (controlledResources: ["memory"]).
Common errors and fixes
HPA TARGETS shows <unknown>/60%: failed to get cpu utilization: missing request for cpu
Cause: the target container (including sidecars) has no CPU requests set, or metrics-server data is not ready yet.
kubectl -n myapp describe hpa myapp | sed -n '/Conditions/,$p'
kubectl -n myapp get deploy myapp -o jsonpath='{.spec.template.spec.containers[*].resources}'
Fix: set CPU requests on all containers, then wait 1–2 minutes.
ScaledObject READY=False: scaler connection failed / error establishing connection
Cause: wrong scaler address or authentication, or a NetworkPolicy blocks keda-operator in kube-system from reaching the event source.
kubectl -n myapp describe scaledobject myapp-worker | sed -n '/Events/,$p' kubectl -n kube-system logs deploy/keda-operator --tail=50
Fix: correct the address or authentication; allow traffic from kube-system to the event source; for Workload Identity, check the subject of the federated credential (system:serviceaccount:kube-system:keda-operator).
admission webhook "vscaledobject.keda.sh" denied the request: the workload 'myapp' of type 'apps/v1.Deployment' is already managed by the hpa 'myapp'
Cause: the same workload already has a manual HPA.
Fix: run kubectl -n myapp delete hpa myapp, then create the ScaledObject (KEDA generates keda-hpa-*).
Pod stays Pending after a VPA recommendation takes effect (Insufficient memory)
Cause: VPA raised requests above what a single node's allocatable can hold, or the node pool has reached max.
Fix: set maxAllowed below the largest node's allocatable; run on NAP or large-SKU pools; or use InPlaceOrRecreate and accept fallback to eviction.
keda-operator OOMKilled, all ScaledObjects stop scaling
Cause: a large number of ScaledObjects/scalers increases the operator's memory usage, and the add-on does not allow changing its resource settings.
Fix: official recommendation: enable VPA and create a VPA for keda-operator with updateMode: InPlaceOrRecreate. Also merge duplicate ScaledObjects, and increase pollingInterval where appropriate.
1. Verify that the KEDA add-on is enabled, and check the installed KEDA version.
az aks show -g $RG -n $CLUSTER --query "workloadAutoScalerProfile.keda.enabled"
kubectl get crd scaledobjects.keda.sh -o jsonpath='{.metadata.labels.app\.kubernetes\.io/version}{"\n"}'2. View the VPA Target recommendation for myapp.
kubectl -n myapp get vpa myapp-vpa -o jsonpath='{.status.recommendation.containerRecommendations[0].target}{"\n"}'The queue has a backlog of 10,000 messages. The ScaledObject max is 50, but only 12 workers are running and the rest are Pending. How do you analyze this?
KEDA/HPA has already raised the replicas to 50, so the bottleneck is at the node layer: ① check the Pending events (insufficient cpu? taints?); ② CA: has the pool reached max-count, is quota insufficient, or is there NotTriggerScaleUp? NAP: have the NodePool limits been used up, and are the SKUs available? ③ subnet IPs (Node Subnet mode). Fix the matching node-layer limit, or prepare a Spot or NAP batch pool for the workers.
Verified instructional videos
Official documentation
- Install the KEDA add-on using Azure CLI
- Use the Vertical Pod Autoscaler in AKS
- AKS component version table (KEDA/VPA versions)
- KEDA scalers
- Horizontal Pod Autoscaling
Video storyboard script (about 90 seconds)
This course file cannot generate a video or MP3 directly. A storyboard and narration script are provided, which you can hand to a video tool.
Visual: the HPA formula lights up step by step: 3 × 148 ÷ 60 = 7.4, rounded up to 8.
Narration: the HPA multiplies the current replica count by the ratio of current utilization to target utilization, then rounds up. Utilization is calculated relative to requests.
Visual: the bars for the Redis list grow taller, the KEDA operator activates the worker from 0 to 1, and then the HPA it generated scales it up to 12.
Narration: KEDA handles activation from zero to one, and passes the queue length to the HPA it generates as an external metric. That HPA then handles scaling from one to many.
Visual: some workers turn yellow as Pending, then turn green once the node pool adds new nodes.
Narration: when replicas don't fit, the node-level autoscaler takes over.
Visual: the VPA recommendation card shows Target 163m / 174Mi, and the mode switches to InPlaceOrRecreate.
Narration: VPA adjusts the size of each pod. When used together with HPA, don't let them control the same metric.
Module 5 · Spot node pools and cost optimization
- Create a Spot node pool and explain
--priority Spot,--eviction-policy Delete|Deallocate, and--spot-max-price(-1 means no price-based eviction), including that they cannot be changed after creation. - Know the label
kubernetes.azure.com/scalesetpriority: spotand the taintkubernetes.azure.com/scalesetpriority=spot:NoSchedulethat AKS adds automatically, and write the correct toleration and affinity. - Design a "prefer Spot, fall back to regular pools" approach (CA with multiple pools, or NAP capacity-type), and list other cost levers: right-sizing requests, scaling to 0, consolidation, reserved instances / savings plans, stopping the cluster, and the cost analysis add-on.
What: Spot node pools
Spot node pools are backed by Azure Spot VMSS and billed at variable Spot prices. Azure evicts nodes when it needs to reclaim capacity, or when the price exceeds your max price. There is no SLA and no high-availability guarantee.
Official limitations (verified 2026-11)
- A Spot pool cannot be the default (first) node pool; it can only be an additional user pool. The cluster must use VMSS and a Standard LB.
priority,eviction-policy, andspot-max-pricecannot be changed after creation. The max price must be-1or a positive number with at most 5 decimal places (USD per hour).- AKS automatically adds the label
kubernetes.azure.com/scalesetpriority:spotand the taintkubernetes.azure.com/scalesetpriority=spot:NoSchedule; system pods have anti-affinity toward Spot. - You cannot upgrade the control plane and a Spot pool at the same time. When a Spot pool is upgraded, AKS cordons it and sends eviction notifications, but it does not drain and has no surge nodes.
- With the
Deallocateeviction policy, stopped instances still count against compute quota, which can cause scale-up or upgrade failures. Usually chooseDelete(the default).
Why: why it's worth using
Spot prices are usually well below on-demand prices (the discount varies by region, SKU, and time; see the pricing page). Batch processing, CI builds, test environments, retryable data processing, and stateless helper services with multi-replica redundancy are all good fits.
How: what happens during an eviction
- Azure sends a
Preemptevent through Scheduled Events (Spot VMs usually get up to about 30 seconds of notice), and then deletes (or deallocates) the VM. - The node becomes NotReady or disappears, the pods on it lose their runtime, and their controllers recreate them elsewhere, so they may go Pending.
- When CA finds that the pool has fewer nodes than needed (or below min-count), it tries to scale up the Spot pool again. If Spot capacity keeps running short, fall back to a regular pool (see below). Without CA, the Spot pool eventually scales to 0 and needs manual intervention.
Three approaches to "prefer Spot, fall back to regular"
| Approach | How to implement | Notes |
|---|---|---|
| A. Pods prefer Spot | Pods tolerate the Spot taint + a preferredDuringScheduling affinity for Spot nodes; they can also schedule onto regular pools | When CA scales up, the expander decides which pool is used, which is not necessarily the Spot pool |
| B. CA priority expander | expander=priority + the cluster-autoscaler-priority-expander ConfigMap in kube-system (regex priority set higher for Spot pools) | The AKS documentation only lists priority as an option. For ConfigMap details, refer to the upstream FAQ and AKS support, and always verify before production. |
| C. NAP | NodePool karpenter.sh/capacity-type: [spot, on-demand]: when both are allowed, NAP prefers Spot and chooses on-demand if Spot is unavailable | Simplest; NAP network requirements must be met |
When: which workloads should not use Spot
- Single-replica stateful services, database primaries, long-running tasks that cannot be interrupted (no checkpointing), and components in the system pool.
- Latency-critical online services without sufficient redundancy.
Cost optimization toolkit
| Lever | Effect | Where it appears in this course |
|---|---|---|
| Right-size requests (VPA recommendations) | Reduces capacity that is reserved but unused | Module 4 |
| CA with a sensible profile / NAP consolidation | Reclaims idle nodes promptly and switches to smaller sizes | Modules 2 and 3 |
| KEDA scale-to-0 + user pool min 0 | Zero cost at night / when idle | Module 4 |
| Spot pool / NAP spot | Large discount for batch work | This module |
| Reserved instances / Azure savings plans | Discount on stable baseline capacity (billing-level, unrelated to cluster configuration) | — |
Dev clusters: az aks stop; pool scaleDownMode: Deallocate | Only disk costs while stopped | Module 0 |
Cost analysis add-on (az aks update --enable-cost-analysis, requires Standard/Premium tier) | Allocates cost by namespace/workload | Hour 6 |
Comparison with similar practices
| AKS Spot pools | AWS Spot (EKS) | GCP Spot VMs (GKE) | |
|---|---|---|---|
| Eviction notice | Scheduled Events (about 30 seconds) | 2-minute interruption notice | About 30 seconds |
| Automatic taint | Yes (scalesetpriority=spot) | No (configure yourself) | Optional |
| Price cap | Max price or -1 can be set | Can be set | None |
Architecture diagram: division of work between Spot and regular pools
Flowchart: recovery process after a Spot eviction
Interactive simulator: Spot eviction and fallback
A Job with 12 parallel tasks runs on a Spot pool (4 tasks per node). Click "Evict one Spot node" or "Spot capacity exhausted" to watch how pods, CA, and the fallback policy react. Switch the fallback policy to compare results.
Core commands and parameters
| Parameter | Values | Description |
|---|---|---|
--priority | Regular (default) / Spot | Cannot be changed after creation |
--eviction-policy | Delete (default) / Deallocate | Deallocate still uses quota |
--spot-max-price | -1 or a positive number (≤5 decimal places) | -1: no price-based eviction |
--enable-cluster-autoscaler --min-count 0 --max-count N | — | Officially recommended for use with Spot |
az aks nodepool add -g $RG --cluster-name $CLUSTER -n spotpool \
--priority Spot --eviction-policy Delete --spot-max-price -1 \
--node-vm-size Standard_D8as_v5 --os-sku AzureLinux --max-pods 110 \
--labels workload=batch \
--enable-cluster-autoscaler --min-count 0 --max-count 6 --node-count 1
az aks nodepool show -g $RG --cluster-name $CLUSTER -n spotpool \
--query "{priority:scaleSetPriority, eviction:scaleSetEvictionPolicy, maxPrice:spotMaxPrice, labels:nodeLabels, taints:nodeTaints}" -o jsonc
{
"eviction": "Delete",
"labels": { "kubernetes.azure.com/scalesetpriority": "spot", "workload": "batch" },
"maxPrice": -1.0,
"priority": "Spot",
"taints": [ "kubernetes.azure.com/scalesetpriority=spot:NoSchedule" ]
}
Pod side: toleration + affinity
tolerations:
- key: "kubernetes.azure.com/scalesetpriority"
operator: "Equal"
value: "spot"
effect: "NoSchedule"
affinity:
nodeAffinity:
# Option A: prefer Spot, but allow fallback to the regular pool
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- { key: kubernetes.azure.com/scalesetpriority, operator: In, values: ["spot"] }
# To run only on Spot, switch to requiredDuringSchedulingIgnoredDuringExecution
How to verify: run kubectl get pod -o wide and check whether NODE is aks-spotpool-*. Common mistake: adding the toleration without the affinity. A toleration only allows the Pod on Spot nodes. The scheduler can still place it in the regular pool. Production use: CI runners, reporting, ETL, and batch model inference.
Query Spot prices (retail price API)
curl -s "https://prices.azure.com/api/retail/prices?\$filter=armRegionName%20eq%20'canadacentral'%20and%20armSkuName%20eq%20'Standard_D8as_v5'%20and%20priceType%20eq%20'Consumption'" \
| jq -r '.Items[] | select(.productName|test("Linux|Virtual Machines Dasv5 Series$")) | [.skuName, .retailPrice, .unitOfMeasure] | @tsv'
In the output, the D8as v5 Spot and D8as v5 rows are the retail prices for Spot and on-demand (USD, which changes over time; ignore the Windows price rows).
Lab 5: Add a Spot pool, run an interruptible Job, and simulate eviction (about 15 minutes)
SkuNotAvailable / allocation failure). You can switch to D4as_v5 or D8s_v5. A simulated eviction deletes the Pods running on that VM.apiVersion: batch/v1
kind: Job
metadata: { name: report, namespace: myapp }
spec:
completions: 12
parallelism: 12
completionMode: Indexed
backoffLimitPerIndex: 3
template:
spec:
restartPolicy: Never
tolerations:
- { key: kubernetes.azure.com/scalesetpriority, operator: Equal, value: spot, effect: NoSchedule }
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- { key: kubernetes.azure.com/scalesetpriority, operator: In, values: ["spot"] }
containers:
- name: work
image: busybox:1.37
command: ["sh", "-c", "echo index=$JOB_COMPLETION_INDEX; sleep 240"]
resources: { requests: { cpu: "1500m", memory: 1Gi } }
kubectl apply -f spot-job.yaml kubectl -n myapp get pod -l job-name=report -o wide kubectl get nodes -l kubernetes.azure.com/scalesetpriority=spot
12 × 1.5 cores = 18 cores. CA will scale spotpool to about 3 VMs (each D8as_v5 has about 7.8 allocatable cores).
NRG=$(az aks show -g $RG -n $CLUSTER --query nodeResourceGroup -o tsv) VMSS=$(az vmss list -g $NRG --query "[?contains(name,'spotpool')].name" -o tsv) az vmss list-instances -g $NRG -n $VMSS --query "[].instanceId" -o tsv az vmss simulate-eviction -g $NRG -n $VMSS --instance-id 0 kubectl get nodes -l kubernetes.azure.com/scalesetpriority=spot -w
What to observe: after the node goes NotReady and disappears, the task Pods on it fail. backoffLimitPerIndex retries the failed indexes, and CA scales the Spot pool back up. az vmss simulate-eviction is the Azure operation that simulates a Spot eviction (Spot instances only).
kubectl -n myapp get job report -o jsonpath='{.status.succeeded}/{.spec.completions} failedIndexes={.status.failedIndexes}{"\n"}'kubectl -n myapp delete job report. The Spot pool has min 0, so CA scales it down to 0 when it is idle. To delete the pool: az aks nodepool delete -g $RG --cluster-name $CLUSTER -n spotpool --no-wait.Case 1: Move all CI builds to Spot
Problem: self-hosted GitHub Actions runners (ARC) occupy 40 cores of on-demand nodes during the day. Approach: runner Pods tolerate Spot and require affinity to the Spot pool. CA scales between 0 and 30. The CI system automatically retries jobs that get evicted. Limitation: long builds (over 1 hour) are costly when evicted, so split them into steps and cache the artifacts.
Case 2: A 'mixed deployment' of an online service causes instability across the whole service
Problem: to save money, half of myapp's replicas were set to prefer Spot. One day a regional Spot reclaim removed 6 replicas at once, and the remaining replicas were overloaded. Approach: keep the baseline of the online service on the regular pool (the replicas at minReplicas must run on the regular pool), and put only the elastic part above the baseline on Spot. Use topologySpread on kubernetes.azure.com/scalesetpriority to control the ratio. Limitation: topology spread only applies at scheduling time. After evictions, you need the descheduler or a redeploy to return to the ideal ratio.
Case 3: A Deallocate policy exhausts the quota
Problem: the Spot pool used the Deallocate policy. After many evictions it accumulated a large number of stopped-deallocated instances that consumed vCPU quota, so scale-out of the regular pool failed. Approach: create a new Spot pool with the Delete policy and migrate to it (the policy cannot be changed).
Common errors and fixes
Pod Pending: 0/6 nodes are available: 3 node(s) had untolerated taint {kubernetes.azure.com/scalesetpriority: spot}, ...
Cause: the Pod has no Spot toleration, so it can only go to the regular pool, and that pool is full. Or you wanted the Pod on Spot in the first place.
Fix: add a toleration for interruptible workloads (the key, value, and effect must match exactly), and pair it with affinity.
Failed to create the Spot pool: (SkuNotAvailable) / OverconstrainedAllocationRequest / no Spot capacity
Cause: the region or zone has insufficient Spot capacity, or this VM size is not offered as Spot.
az vm list-skus -l $LOC --size Standard_D8as_v5 --query "[].{name:name,restrictions:restrictions}" -o jsonc
Fix: change the VM size (prepare several Spot pools, or use NAP's multi-SKU selection), or change the zone. Do not pin a single availability zone.
The Spot pool node count stays at 0, even with Pending Pods that tolerate Spot
Cause: CA is not enabled on the Spot pool (so it is not scaled back up after evictions), or the pool has reached max-count, or the expander chose a different pool.
az aks nodepool show -g $RG --cluster-name $CLUSTER -n spotpool --query "{auto:enableAutoScaling,min:minCount,max:maxCount,count:count}"
kubectl get events -A --field-selector source=cluster-autoscaler --sort-by=.lastTimestamp | tail
Fix: enable CA, and check the reason in NotTriggerScaleUp.
(InvalidParameter) Failed to modify spotMaxPrice / priority on the Spot pool
Cause: these properties can only be set at creation time.
Fix: create a new pool, migrate the workloads, then delete the old pool.
During an upgrade, Pods on the Spot pool are interrupted immediately (no drain)
Cause: this is expected behavior. A Spot pool upgrade only cordons nodes and sends eviction notices. It does not drain and does not use surge.
Fix: before upgrading, drain critical tasks or pause job submission. Spot workloads themselves must be able to tolerate interruption.
1. Add a Spot pool that does not evict based on price, deletes VMs on eviction, and has CA 0–5.
az aks nodepool add -g $RG --cluster-name $CLUSTER -n spot2 --priority Spot --eviction-policy Delete --spot-max-price -1 --enable-cluster-autoscaler --min-count 0 --max-count 5 --node-count 1
2. List all Spot nodes and the number of Pods running on each.
for n in $(kubectl get nodes -l kubernetes.azure.com/scalesetpriority=spot -o name); do echo "$n $(kubectl get pod -A --field-selector spec.nodeName=${n#node/} --no-headers | wc -l)"; doneYour boss asks you to 'put all services on Spot to save 70%'. How do you respond, and how would you design it?
Spot has no SLA, PDBs cannot stop evictions, and the system pool cannot be Spot. Recommendations: (1) keep the system pool and the baseline replicas of online services on the regular pool (reserved instances or savings plans can lower the price); (2) put the elastic part, batch jobs, CI, and test environments on Spot; (3) use the NAP capacity-type setting or multiple pools as a fallback; (4) use the cost analysis add-on to quantify the savings.
Teaching videos
No verified official video on Spot node pools was found (none on the AKS official channel; the community video channels in search results are small and were not included). For the AKS scaling deep-dive video from the official channel, see Module 2. The storyboard script below can also be used.
Official documentation
- Add an Azure Spot node pool to an AKS cluster
- Azure Spot Virtual Machines for scale sets
- NAP capacity-type selector
Video storyboard (about 80 seconds)
This course file cannot generate a video or MP3 directly. A storyboard and narration script are provided, which you can hand to a video tool.
Visual: two rows of nodes. Regular nodes are blue, and Spot nodes are orange with a 'spot:NoSchedule' label.
Narration: Spot node pools use Azure's spare capacity. They are cheap, but they come with no service-level agreement. AKS adds a taint to them automatically.
Visual: a Job Pod with a toleration and affinity lands on a Spot node. An online service Pod is kept out of the regular pool by a taint.
Narration: only workloads with a toleration can run on Spot. Node affinity makes sure they actually land there.
Visual: lightning strikes a Spot node. After a 30-second countdown it disappears, the Pod turns Pending, and CA scales back up.
Narration: an eviction gives only about thirty seconds of notice, and a PDB cannot block it. The cluster autoscaler adds nodes back.
Visual: Spot capacity runs out, and Pods flow to the regular pool (dashed arrows).
Narration: you have to design the fallback yourself. Use preferred affinity, a priority expander, or node auto-provisioning that allows both Spot and on-demand.
Module 6 · GPU and specialized workloads
- Tell apart three GPU installation setups: fully managed (driver + device plugin + DCGM exporter + health signals), driver only (the default), and BYO (
--gpu-driver None, used with the NVIDIA GPU Operator). - Create a GPU node pool (minimum recommended:
Standard_NC4as_T4_v3). Isolate it with thesku=gpu:NoScheduletaint, and have Pods request resources withnvidia.com/gpu. Understand the MIG strategies (None, Single, and Mixed). - Use CA (min 0) or NAP (
sku-family N+sku-gpu-manufacturer nvidia) to scale GPUs on demand.
What: the components that run GPUs on AKS
| Component | Purpose | Fully managed | Driver only (default) | BYO |
|---|---|---|---|---|
| NVIDIA GPU driver | Kernel module and user-space libraries | AKS | AKS | You (for example, the GPU Operator) |
| NVIDIA device plugin | Advertises nvidia.com/gpu to the kubelet (nvidia.com/mig-* when MIG is used) | AKS | You | You |
| DCGM + DCGM exporter | GPU utilization, temperature, and other Prometheus metrics (port 19400) | AKS (node label kubernetes.azure.com/dcgm-exporter=enabled) | You | You |
| GPU health signals | NPD node conditions UnhealthyNvidiaDevicePlugin and UnhealthyNvidiaDCGMServices | AKS | — | — |
| CLI | --enable-managed-gpu=true | No flag, or --enable-managed-gpu=false | --enable-managed-gpu=false --gpu-driver None |
Note: in driver-only mode there is no device plugin, so the node does not advertise nvidia.com/gpu. GPU Pods stay Pending until you deploy a device plugin. managementMode, migStrategy, and driver are fixed at creation and cannot be changed. You also cannot turn an existing general-purpose pool into a GPU pool.
Why: why GPU nodes need a dedicated design
- Expensive: a GPU VM costs several to dozens of times more than a general-purpose VM, so idle time is the most costly. It must be able to scale to 0.
- Scarce: regional and zonal capacity is limited, and allocation failures are common. You need multiple VM sizes or capacity reservations.
- Slow: node startup, the driver, and pulling large images (CUDA and PyTorch images often run to several GB) can take more than 10 minutes on a cold start.
How: the scheduling path for a GPU Pod
- The Pod declares
resources.limits: nvidia.com/gpu: 1and a toleration forsku=gpu. - Scheduler filter: only nodes that advertise an allocatable
nvidia.com/gpupass. If there are no GPU nodes, the Pod stays Pending. - CA simulates the node using the GPU pool's template (the template includes the GPU extended resource) and scales up the GPU pool. NAP selects a SKU that meets the N-series requirements of the NodePool.
- The node starts, and AKS installs the driver (in managed mode, it also deploys the device plugin and DCGM). The device plugin registers through the kubelet's Device Plugin gRPC interface and advertises the GPU count.
- The scheduler binds the Pod. The kubelet calls the device plugin's
Allocatemethod, which injects the GPU device and libraries into the container (NVIDIA container toolkit).
MIG (Multi-Instance GPU)
SKUs that support MIG, such as A100 and H100, can be split into multiple instances. Use --gpu-instance-profile MIG1g with --gpu-mig-strategy Single (still requested as nvidia.com/gpu), or with Mixed (requested as nvidia.com/mig-1g.10gb and similar). An existing MIG pool cannot be migrated to managed GPU.
When: how to choose
- Most scenarios: AKS managed GPU node pool (officially recommended).
- If you need precise control over driver and device plugin versions, or you standardize on the NVIDIA GPU Operator: BYO.
- Mixed workloads (T4 or A10 for inference, A100 for training): a NAP NodePool (N-series) plus an AKSNodeClass with
gpu.mode: Driverandnvidia.managementMode: Managed(requires the AKS Machine API provisioning mode). - OS: Ubuntu and Azure Linux both support GPUs. Flatcar and Azure Linux with OS Guard do not support NVIDIA GPUs. Azure Linux GPU pools do not receive security patches automatically, so watch the node OS upgrade channel. AKS does not support AMD NVv4 series.
Comparison with similar practices
| AKS managed GPU | NVIDIA GPU Operator | KAITO (AI toolchain add-on) | |
|---|---|---|---|
| Scope | Driver + device plugin + DCGM | Full stack: driver, toolkit, plugin, DCGM, and MIG manager | Automatically provisions GPU nodes per model and deploys inference |
| Operations | AKS handles it | You handle it | AKS add-on (not covered in this hour) |
nvidia.com/gpu by default.' The default is driver only, which has no device plugin. (2) '--skip-gpu-driver-install skips the driver.' That flag stopped being supported on 2025-08-14. Use --gpu-driver none instead. (3) 'GPUs can be overcommitted like CPUs (requests < limits).' Extended resources must be whole numbers, and requests must equal limits. (4) 'Setting the GPU pool min to 1 is safer.' That is the most expensive form of insurance. Prefer min 0 with warm-up or capacity reservations.Architecture diagram: software stack for AKS managed GPU nodes
Flowchart: cold start when the GPU pool scales to 0
Step-by-step animation: a GPU Pod from Pending to nvidia-smi
After you choose an installation setup, play through the steps. Observe which components AKS installs, when it advertises nvidia.com/gpu, and why the 'driver only' mode gets stuck.
Core commands and parameters
| Parameter | Description |
|---|---|
--node-vm-size Standard_NC4as_T4_v3 | Minimum recommended AKS GPU pool size (1×T4) |
--enable-managed-gpu=true|false | Fully managed stack / driver only (CLI ≥ 2.85.0) |
--gpu-driver None | Do not install the driver (use with --enable-managed-gpu=false; CLI ≥ 2.72.2) |
--gpu-instance-profile MIG1g --gpu-mig-strategy Single|Mixed | MIG (A100/H100) |
--node-taints sku=gpu:NoSchedule | Isolation (can only be set at creation) |
az aks nodepool add -g $RG --cluster-name $CLUSTER -n gpupool \ --node-vm-size Standard_NC4as_T4_v3 --node-count 1 \ --node-taints sku=gpu:NoSchedule --labels workload=gpu \ --enable-managed-gpu=true \ --enable-cluster-autoscaler --min-count 0 --max-count 2 az aks nodepool show -g $RG --cluster-name $CLUSTER -n gpupool --query gpuProfile -o jsonc
{
"driver": "Install",
"driverType": "",
"nvidia": {
"managementMode": "Managed",
"migStrategy": null
}
}
Verify the managed stack
GPU_NODE=$(kubectl get nodes -l agentpool=gpupool -o jsonpath='{.items[0].metadata.name}')
kubectl get node $GPU_NODE -o jsonpath='{.status.allocatable.nvidia\.com/gpu}{" dcgm="}{.metadata.labels.kubernetes\.azure\.com/dcgm-exporter}{"\n"}'
kubectl describe node $GPU_NODE | grep -E "UnhealthyNvidia"
1 dcgm=enabled UnhealthyNvidiaDevicePlugin False ... HealthyNvidiaDevicePlugin ... UnhealthyNvidiaDCGMServices False ... HealthyNvidiaDCGMServices ...
Test Pod (official sample image)
apiVersion: v1
kind: Pod
metadata: { name: managed-gpu-test, namespace: myapp }
spec:
restartPolicy: Never
tolerations:
- { key: "sku", operator: "Equal", value: "gpu", effect: "NoSchedule" }
nodeSelector: { workload: gpu }
containers:
- name: gpu-test
image: mcr.microsoft.com/azuredocs/samples-tf-mnist-demo:gpu
command: ["nvidia-smi"]
resources:
limits: { nvidia.com/gpu: 1 }
kubectl apply -f gpu-test.yaml kubectl -n myapp logs managed-gpu-test
NAP approach (managed GPU with AKSNodeClass)
apiVersion: karpenter.azure.com/v1beta1
kind: AKSNodeClass
metadata: { name: managed-gpu-class }
spec:
gpu:
mode: Driver
nvidia: { managementMode: Managed }
---
apiVersion: karpenter.sh/v1
kind: NodePool
metadata: { name: managed-gpu-np }
spec:
limits: { nvidia.com/gpu: "4" }
disruption: { consolidationPolicy: WhenEmpty, consolidateAfter: 10m }
template:
spec:
taints: [ { key: sku, value: gpu, effect: NoSchedule } ]
nodeClassRef: { group: karpenter.azure.com, kind: AKSNodeClass, name: managed-gpu-class }
requirements:
- { key: karpenter.azure.com/sku-family, operator: In, values: ["N"] }
- { key: karpenter.azure.com/sku-gpu-manufacturer, operator: In, values: ["nvidia"] }
- { key: karpenter.sh/capacity-type, operator: In, values: ["on-demand"] }
Official note: managed GPU with NAP requires the AKS Machine API provisioning mode. That NodePool limits can include extended resources (such as nvidia.com/gpu) is a general Karpenter capability. Whether it takes effect depends on the CRD validation in your cluster. To be safe, you can limit only cpu and memory.
Lab 6 (optional): T4 GPU pool + nvidia-smi (about 20 minutes)
az vm list-usage -l $LOC -o table | grep -i T4 (if Limit is 0, request 4 vCPUs on the Quotas page in the portal).kubectl apply -f gpu-test.yaml
kubectl -n myapp wait --for=jsonpath='{.status.phase}'=Succeeded pod/managed-gpu-test --timeout=600s
kubectl -n myapp logs managed-gpu-test | head -15
+-----------------------------------------------------------------------------------------+ | NVIDIA-SMI 570.xx.xx Driver Version: 570.xx.xx CUDA Version: 12.x | |-----------------------------------------+------------------------+----------------------+ | GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC | | 0 Tesla T4 On | 00000001:00:00.0 Off | 0 | +-----------------------------------------+------------------------+----------------------+
kubectl -n myapp delete pod managed-gpu-test; kubectl get nodes -l agentpool=gpupool -w.az aks nodepool delete -g $RG --cluster-name $CLUSTER -n gpupool --no-wait.Case 1: Inference service cold start takes 12 minutes
Problem: the GPU pool has min 0, so the first overnight request waits for the node to boot and for an 8 GB image to pull. Approach: keep one minimum replica for online inference (GPU pool min 1), use a KEDA cron schedule to scale out before working hours, and store the image in a Premium ACR with Artifact Streaming enabled. Limitation: min 1 means paying for 24 hours a day, so weigh that against the SLA.
Case 2: Driver version is incompatible with the CUDA image
Problem: the team uses a CUDA 12.8 image and gets CUDA driver version is insufficient for CUDA runtime version. Approach: check the NVIDIA compatibility matrix. In AKS managed mode, the driver is updated with the node image, so upgrade the node image first. If you need to pin the driver version, switch to BYO with the GPU Operator. Limitation: in BYO mode, Microsoft does not support driver issues.
Case 3: A training platform with several GPU models
Problem: three CA pools (T4, A10, and A100) are maintained. Utilization is low, and one model often runs short of capacity. Approach: switch to NAP with one N-series NodePool (sku-gpu-name In [T4, A10, A100]). Pods select karpenter.azure.com/sku-gpu-name through nodeSelector. Training jobs use WhenEmpty so consolidation does not interrupt them. Limitation: you must meet the NAP networking requirements and the AKS Machine API mode.
Common errors and fixes
0/4 nodes are available: 1 Insufficient nvidia.com/gpu, 3 node(s) had untolerated taint ...
Cause: the GPU node does not advertise nvidia.com/gpu. Either driver-only mode has no device plugin deployed, or the plugin is unhealthy. It is also possible that all GPUs are already in use.
kubectl get nodes -o custom-columns=NAME:.metadata.name,GPU:.status.allocatable.nvidia\\.com/gpu kubectl get ds -A | grep -i nvidia
Fix: create the pool with --enable-managed-gpu=true, or deploy the NVIDIA device plugin DaemonSet manually (make sure it tolerates the sku=gpu taint).
unrecognized arguments: --gpu-driver none
Cause: the Azure CLI version is too old (it needs to be ≥ 2.72.2), or the flag was used with nodepool update/upgrade. This parameter is only for creation.
Fix: run az upgrade, and specify the flag only with nodepool add.
CUDA driver version is insufficient for CUDA runtime version
Cause: the CUDA runtime in the image is newer than the node driver.
kubectl -n myapp exec POD -- nvidia-smi | head -5
Fix: choose an image that is compatible with the driver, or upgrade the node image. In BYO setups, upgrade the driver yourself.
Node condition UnhealthyNvidiaDevicePlugin=True (managed GPU node)
Cause: the managed device plugin is unhealthy (driver load failure, hardware Xid errors, and so on).
kubectl describe node $GPU_NODE | sed -n '/Conditions/,/Addresses/p'
Fix: cordon and drain the node, then reimage it (az aks nodepool upgrade --node-image-only, or delete the VM instance so CA replaces it). If the problem keeps happening, open a support ticket.
(QuotaExceeded) ... Standard NCASv3_T4 Family vCPUs quota
Cause: the GPU quota for this VM series is 0 or too low.
Fix: request quota on the Quotas page in the portal, or switch to a region or VM size that has quota.
1. Create a T4 pool that does not install any GPU components, ready to be used with the GPU Operator.
az aks nodepool add -g $RG --cluster-name $CLUSTER -n gpubyo --node-vm-size Standard_NC4as_T4_v3 --node-count 1 --node-taints sku=gpu:NoSchedule --enable-managed-gpu=false --gpu-driver None
2. List the number of allocatable GPUs on each node.
kubectl get nodes -o custom-columns='NAME:.metadata.name,GPU:.status.allocatable.nvidia\.com/gpu'
The GPU pool has scaled out one node, and the node is Ready, but the GPU Pod is still Pending with the event Insufficient nvidia.com/gpu. What is the most likely cause?
The node does not advertise the GPU extended resource. The pool was created with the default 'driver only' setting, so there is no device plugin (or the plugin DaemonSet does not tolerate the sku=gpu taint). Confirm with kubectl get node -o jsonpath='{.status.allocatable}'. Fix it by deploying a device plugin, or by switching to a new pool created with --enable-managed-gpu=true. In this situation, CA may also keep scaling out (its template assumes a GPU is present), which wastes money.
Verified instructional videos
No verified AKS official channel video on managed GPU node pools was found.
Official documentation
- Create an AKS-managed GPU node pool
- Use GPUs on AKS (self-managed approach)
- Use the NVIDIA GPU Operator
- GPU-optimized VM sizes
Video storyboard (about 80 seconds)
This course file cannot generate a video or MP3 directly. A storyboard and narration script are provided, which you can hand to a video tool.
Visual: a GPU node looks like a three-story building: driver, device plugin, and DCGM. Three colors mark managed, driver-only, and self-managed.
Narration: there are three ways to run GPUs on AKS. The recommended managed mode installs the driver, the device plugin, and the monitoring exporter.
Visual: a Pod requests nvidia.com/gpu: 1. The scheduler checks the node's allocatable resources, and a green light turns on once the device plugin advertises the GPU.
Narration: the scheduler places a GPU Pod only after the device plugin has advertised the GPU resource.
Visual: the sku=gpu taint blocks ordinary Pods. The GPU pool scales from 0 to 1, and a timer shows several minutes.
Narration: a taint isolates the expensive GPU nodes, and autoscaling lets the pool scale to zero when it is idle.
Visual: the terminal prints nvidia-smi output showing a Tesla T4.
Narration: finally, nvidia-smi confirms that the container really has the GPU.
Module 7 · Availability: PDBs, topology spread, and zone redundancy
- List which operations go through the Eviction API and are protected by PDBs:
kubectl drain, CA scale-down, NAP consolidation and drift, node pool upgrades, and OS SKU migration. List what is not protected: Spot eviction, node or zone failures, deleting Pods directly, and Deployment rolling updates. - Write cross-zone and cross-node
topologySpreadConstraintsfor myapp. UnderstandmaxSkew,whenUnsatisfiable,minDomains, andmatchLabelKeys. - Design zone redundancy with zone-spanning node pools, ZRS disks, and Standard LB. Run a 'zone failure' drill (cordon and drain one zone).
What: three lines of defense
| Mechanism | What it protects | Key fields |
|---|---|---|
| PodDisruptionBudget | Number of replicas that can be unavailable at the same time during voluntary disruptions | minAvailable or maxUnavailable; unhealthyPodEvictionPolicy: AlwaysAllow |
| topologySpreadConstraints | Distribution of replicas across zones and nodes | topologyKey, maxSkew, whenUnsatisfiable, minDomains, matchLabelKeys |
| Zone redundancy (infrastructure) | Failure of a single datacenter | Node pool --zones 1 2 3, ZRS disks, zone-redundant LB; the control plane is replicated across zones by Microsoft |
Why: autoscaling makes disruptions frequent
Without autoscaling, a node is drained only a few times a year, mainly for upgrades. Once CA and NAP are enabled, scale-down, consolidation, and drift can evict Pods every day. Without a PDB, CA can drain both nodes that hold all the replicas of a service at once. Without topology spread, the 10 replicas added by HPA may all land in zone 1.
How: the mechanics
PDBs and the Eviction API
- Eviction callers (drain, CA, Karpenter, AKS upgrades) call
POST /api/v1/namespaces/{ns}/pods/{name}/eviction. The API server checks the PDB'sstatus.disruptionsAllowed. When it is 0, the API server returns 429 Too Many Requests, and the caller waits and retries. - CA scale-down waits up to
max-graceful-termination-sec(default 600 seconds). When NAP'sterminationGracePeriodexpires, it bypasses the PDB. AKS upgrades havedrainTimeoutInMinutesandundrainableNodeBehavior(see hour 6). unhealthyPodEvictionPolicy: AlwaysAllow: unhealthy Pods can be evicted directly, so a broken Pod cannot block a drain. This setting is officially recommended.- Not protected by PDBs: Spot eviction, VM or zone failures, OOM kills, direct
kubectl delete pod, and the Deployment's own rolling updates (controlled by maxUnavailable).
Topology spread
- AKS nodes carry labels such as
topology.kubernetes.io/zone=canadacentral-1(the value shows as0for regional pools). - Use
whenUnsatisfiable: DoNotSchedule(hard constraint) across zones andScheduleAnyway(soft constraint) across nodes, so Pods do not stay Pending when there are not enough nodes. nodeTaintsPolicy: Honor(node inclusion policy; enabled by default since 1.26, follow the K8s docs): when computing topology domains, ignore nodes whose taints the Pod does not tolerate. With the defaultIgnore, a cordoned node (with thenode.kubernetes.io/unschedulabletaint) still counts as a domain. When you drain an entire zone, the replacement replicas then stay Pending because of skew violations, the PDB drops to 0, and the drain gets stuck.minDomains: 3: if fewer than 3 schedulable zones exist, the extra Pods stay Pending. This can warn you that a zone is missing or trigger scale-out. However, it also prevents completing a zone drain, so use it carefully during planned zone maintenance.matchLabelKeys: [pod-template-hash]: during a rolling update, only count Pods of the same version, so old and new versions do not interfere with each other.- CA understands topology constraints. Scaling a zone-spanning pool cannot guarantee that new nodes land in the target zone. That is why the official guidance recommends 'one pool per zone +
balance-similar-node-groups'. NAP uses the zone as a requirement on the NodeClaim and selects it directly. - Topology spread only applies at scheduling time. Later evictions or failures can cause skew, so you need to rebalance (for example with the descheduler, or by redeploying).
Zone redundancy checklist
- Both the system pool and user pools use
--zones 1 2 3. The availability zones cannot be changed after the pool is created. - Storage: in K8s 1.29+,
managed-csiuses ZRS managed disks by default, and they can attach across zones. LRS disks cannot be attached to nodes in other zones. - Entry point: Standard LB spans zones by default. Basic LB was retired on 2025-09-30.
- Control plane: replicated across zones by Microsoft. The Standard and Premium tiers provide a financially backed SLA (hour 1).
- Redis (used by myapp): a single replica is a single point of failure. Production should use Azure Managed Redis or a solution with replication.
When: recommended baseline (stateless services)
- At least 3 replicas (at least 1 per zone); PDB
maxUnavailable: 1(or 20%) +AlwaysAllow; DoNotSchedule across zones + ScheduleAnyway across nodes; readinessProbe and preStop (K8s hour 2).
Comparison with similar practices
| PDB | Deployment maxUnavailable | podAntiAffinity | |
|---|---|---|---|
| When it applies | External eviction | Own rolling update | At scheduling time |
| Granularity | Available count for a group of Pods | Speed of replacing old with new ReplicaSets | Who not to co-locate with |
| Common pitfalls | Setting it to 0 blocks scale-down and upgrades | Unrelated to PDBs | When required, the replica count is limited by the number of domains |
minAvailable: 100% is the safest.' It blocks every voluntary disruption, so CA does not scale down and upgrades get stuck (AKS upgrades fail or follow the undrainable policy when nodes cannot be drained). (3) 'A zone-spanning pool plus topology constraints makes CA scale up in the missing zone.' It does not guarantee that. Use one pool per zone, or use NAP. (4) 'A single replica with PDB maxUnavailable 0 is highly available.' A single replica is never highly available.Architecture diagram: cross-zone deployment of myapp
Flowchart: how the PDB decides on an eviction request
Interactive simulator: availability zone failure and drain
Six myapp replicas are spread across 3 zones. Switch the 'topology spread' and 'PDB' settings, then perform an action: drain one node (through the Eviction API) or fail one zone (not through the Eviction API). Observe the number of available replicas and the recovery process.
Core commands and parameters
| Command | Purpose | Description |
|---|---|---|
kubectl get pdb -A | Check ALLOWED DISRUPTIONS | A PDB with 0 blocks scale-down and upgrades |
kubectl drain NODE --ignore-daemonsets --delete-emptydir-data | Manual drain | --timeout, --disable-eviction (bypasses the PDB; use with caution) |
kubectl get pod -o wide -L topology.kubernetes.io/zone | Which node a Pod is on | Zone labels are on the nodes; see the script below |
kubectl get nodes -L topology.kubernetes.io/zone | Zone of the node | Regional pool shows 0 |
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: myapp, namespace: myapp }
spec:
maxUnavailable: 1
unhealthyPodEvictionPolicy: AlwaysAllow
selector: { matchLabels: { app: myapp } }
---
# Append to spec.template.spec of the myapp Deployment
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
nodeTaintsPolicy: Honor # cordoned or failed nodes are not counted in the topology domain
labelSelector: { matchLabels: { app: myapp } }
matchLabelKeys: ["pod-template-hash"]
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector: { matchLabels: { app: myapp } }
matchLabelKeys: ["pod-template-hash"]
kubectl apply -f - <<'EOF'
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: myapp, namespace: myapp }
spec:
maxUnavailable: 1
unhealthyPodEvictionPolicy: AlwaysAllow
selector: { matchLabels: { app: myapp } }
EOF
kubectl -n myapp patch deploy myapp --type merge -p '{"spec":{"replicas":6,"template":{"spec":{"topologySpreadConstraints":[{"maxSkew":1,"topologyKey":"topology.kubernetes.io/zone","whenUnsatisfiable":"DoNotSchedule","nodeTaintsPolicy":"Honor","labelSelector":{"matchLabels":{"app":"myapp"}},"matchLabelKeys":["pod-template-hash"]},{"maxSkew":1,"topologyKey":"kubernetes.io/hostname","whenUnsatisfiable":"ScheduleAnyway","labelSelector":{"matchLabels":{"app":"myapp"}},"matchLabelKeys":["pod-template-hash"]}]}}}}'
kubectl -n myapp rollout status deploy/myapp
# Replica count per zone
for p in $(kubectl -n myapp get pod -l app=myapp -o jsonpath='{range .items[*]}{.spec.nodeName}{"\n"}{end}'); do kubectl get node $p -o jsonpath='{.metadata.labels.topology\.kubernetes\.io/zone}{"\n"}'; done | sort | uniq -c
2 canadacentral-1
2 canadacentral-2
2 canadacentral-3
How to verify: kubectl -n myapp get pdb myapp should show ALLOWED DISRUPTIONS 1. Common mistakes: without nodeTaintsPolicy: Honor, draining an entire zone gets stuck (see the lab). If myapp still has the nodeSelector from Module 1 (workload=general), the userpool must have nodes in all three zones. Production use: the baseline template for every multi-replica online service. It can be distributed with a Helm chart (see the Helm course).
Lab 7: Cross-zone deployment + PDB + zone drain drill (about 15 minutes)
kubectl -n myapp run probe --image=busybox:1.37 --restart=Never -- /bin/sh -c 'ok=0; bad=0; while true; do if wget -q -T 2 -O /dev/null http://myapp/healthz; then ok=$((ok+1)); else bad=$((bad+1)); fi; echo "ok=$ok bad=$bad"; sleep 0.5; done' kubectl -n myapp logs -f probe
Z1=$(kubectl get nodes -l agentpool=userpool,topology.kubernetes.io/zone=canadacentral-1 -o name)
kubectl cordon $Z1
for n in $Z1; do kubectl drain ${n#node/} --ignore-daemonsets --delete-emptydir-data --timeout=5m; done
kubectl -n myapp get pod -l app=myapp -o wide
evicting pod myapp/myapp-6c9d8b7f5-2kq7x error when evicting pods/"myapp-6c9d8b7f5-9tmrz" -n "myapp" (will retry after 5s): Cannot evict pod as it would violate the pod's disruption budget. pod/myapp-6c9d8b7f5-2kq7x evicted pod/myapp-6c9d8b7f5-9tmrz evicted node/aks-userpool-27182818-vmss000000 drained
Because nodeTaintsPolicy: Honor is set, the cordoned zone 1 nodes no longer count in the topology domain. Replacement replicas are placed in zones 2 and 3 with skew ≤ 1 (ending at 3/3). The PDB makes the evictions happen one at a time. You may see one 'violate the pod's disruption budget' message followed by a retry. The bad count in the probe log should stay at 0. Optional comparison: remove nodeTaintsPolicy, or add minDomains: 3, and repeat this step. The first replacement replica stays Pending, the PDB allows 0 disruptions, and the drain keeps retrying until --timeout.
kubectl uncordon $Z1. Replicas do not move back to zone 1 automatically, because topology spread only applies at scheduling time. Run kubectl -n myapp rollout restart deploy/myapp to restore the 2/2/2 distribution. Think about it: in a real zone failure, the nodes become NotReady, and Pods are evicted after tolerationSeconds (default 300 seconds) without going through the PDB.kubectl -n myapp delete pod probe. Scale myapp back to 3 replicas with kubectl -n myapp scale deploy myapp --replicas=3 (keep the PDB and topology constraints).Case 1: A node pool upgrade gets stuck draining for 2 hours
Problem: a service has a PDB with minAvailable: 2 and 2 replicas. Every eviction is rejected, and the AKS upgrade stalls. Approach: raise the replicas to 3, change the PDB to maxUnavailable: 1, and add unhealthyPodEvictionPolicy: AlwaysAllow. Limitation: for the upgrade's drainTimeoutInMinutes and undrainableNodeBehavior (Cordon/Schedule), see hour 6.
Case 2: After a zone failure, the replicas added by HPA are all crowded into one zone
Problem: after zone 2 recovered, the replicas added during the incident were all in zones 1 and 3, and they did not rebalance automatically. Approach: add matchLabelKeys to the topology spread, then run kubectl rollout restart after the incident to redistribute the Pods. Evaluate the descheduler's RemovePodsViolatingTopologySpreadConstraint policy.
Case 3: LRS disks prevent StatefulSet recovery across zones
Problem: a custom StorageClass uses Premium_LRS. After the zone where a node sits fails, the Pod cannot attach its disk in another zone. Approach: migrate to ZRS (Premium_ZRS, StandardSSD_ZRS, or the default managed-csi in 1.29+), or use application-level replication (one replica per zone with LRS). Limitation: ZRS has slightly higher write latency, and not all regions support it.
Common errors and fixes
Cannot evict pod as it would violate the pod's disruption budget.
Cause: the PDB currently has disruptionsAllowed=0 (not enough replicas, Pods are not ready, or the PDB is too strict).
kubectl get pdb -A -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,MIN:.spec.minAvailable,MAXU:.spec.maxUnavailable,ALLOWED:.status.disruptionsAllowed,CURRENT:.status.currentHealthy,DESIRED:.status.desiredHealthy
Fix: add replicas, fix unready Pods, loosen the PDB, or set AlwaysAllow.
0/6 nodes are available: 2 node(s) didn't match pod topology spread constraints (missing required label), 4 node(s) didn't match pod topology spread constraints.
Cause: some nodes lack a valid topology.kubernetes.io/zone label value (it shows 0 for regional pools), or the remaining zones cannot satisfy maxSkew.
kubectl get nodes -L topology.kubernetes.io/zone,agentpool
Fix: use zone-spanning pools for the workload, use nodeSelector to exclude regional pools, or change the cross-zone constraint to ScheduleAnyway.
CA does not scale out in the zone that is missing replicas, and Pods stay Pending because of topology spread
Cause: scaling a zone-spanning pool does not guarantee that the new nodes land in the target zone. After simulation, CA may conclude that scaling out cannot solve the problem (NotTriggerScaleUp).
Fix: switch to one user pool per zone with balance-similar-node-groups=true, or use NAP (the zone is a requirement on the NodeClaim).
Multi-Attach error / volume node affinity conflict (the Pod cannot attach its disk after moving to another zone)
Cause: LRS disks can only attach to nodes in the same zone.
kubectl get pv PV -o jsonpath='{.spec.nodeAffinity}{"\n"}'
kubectl get sc -o custom-columns=NAME:.metadata.name,SKU:.parameters.skuname,BINDING:.volumeBindingMode
Fix: use a ZRS StorageClass, and set WaitForFirstConsumer on the StorageClass.
Drain is stuck: Pod not managed by a controller (cannot delete Pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet)
Cause: a bare Pod, such as one created with kubectl run while debugging. CA also will not scale down a node that has a bare Pod.
Fix: delete it, or switch to a Deployment or Job. If you must force it, use kubectl drain --force, but the bare Pod will be lost.
1. Find all PDBs in the cluster that currently allow no disruptions.
kubectl get pdb -A -o jsonpath='{range .items[?(@.status.disruptionsAllowed==0)]}{.metadata.namespace}/{.metadata.name}{"\n"}{end}'2. Count the myapp replicas in each availability zone.
kubectl -n myapp get pod -l app=myapp -o jsonpath='{range .items[*]}{.spec.nodeName}{"\n"}{end}' | xargs -I{} kubectl get node {} -o jsonpath='{.metadata.labels.topology\.kubernetes\.io/zone}{"\n"}' | sort | uniq -cmyapp has 3 replicas, a PDB with maxUnavailable 1, and DoNotSchedule across zones. Zone 3 fails for 20 minutes. What happens? What extra design is needed?
Zone 3 nodes go NotReady, and after about 5 minutes the replicas on them are evicted (not through the PDB). Rebuilt replicas are subject to maxSkew 1. When the other two zones each have one replica, the third replica can go to either one, because skew only counts domains that have eligible nodes. If minDomains: 3 is set, the replica stays Pending. The remaining 2 replicas carry all the traffic, HPA may scale out, and CA adds nodes in zones 1 and 2. Extra design: plan the replica count so that losing one zone still handles peak load (N+1 zone redundancy), set HPA maxReplicas high enough, leave headroom in the node pool max-count, and make dependencies such as Redis cross-zone as well.
Verified instructional videos
Official documentation
- Configure availability zones in AKS
- Pod Topology Spread Constraints
- Specifying a Disruption Budget
- Best practices for basic scheduler features in AKS
Video storyboard script (about 90 seconds)
This course file cannot generate a video or MP3 directly. A storyboard and narration script are provided, which you can hand to a video tool.
Visual: three zones with two replicas each. A PDB flag above reads 'at most 1 unavailable'.
Narration: the cluster autoscaler moves Pods often. The PDB decides how many can be moved at once.
Visual: one zone is drained. The second eviction request is rejected with a 429, and it proceeds only after the first replica is Ready.
Narration: every operation that uses the eviction API checks the PDB. That includes drain, the cluster autoscaler, node auto-provisioning, and upgrades.
Visual: lightning strikes zone 2. Two replicas disappear at once, and the PDB flag has no effect.
Narration: however, zone failures and Spot evictions do not go through the eviction API, so a PDB cannot stop them. Cross-zone distribution and enough replicas provide the real protection.
Visual: the topology spread configuration is highlighted: maxSkew 1, DoNotSchedule, nodeTaintsPolicy Honor.
Narration: use topology spread constraints to spread replicas evenly across three zones, and pair them with zone-redundant storage to survive the failure of one zone.
Module 8 · Scaling review and common errors
- Review a cluster's scaling design across six dimensions: capacity baseline, Pod scaling, node scaling, cost, availability, and observability.
- Identify the 10 most common scaling errors and their symptoms.
- Use the troubleshooting decision tree and metrics (such as
cluster_autoscaler_unschedulable_pods_count) to locate scaling problems.
What: scaling review checklist
| Dimension | Check item | How to check |
|---|---|---|
| Capacity baseline | All containers have requests; requests are within 2× of actual usage; the system pool is separate and spans at least 3 nodes across zones | VPA Off recommendations, kubectl top, az aks nodepool list |
| Pod scaling | Online services have HPA/KEDA with min ≥ number of zones and a max that is capped; HPA and VPA do not act on the same metric; behavior settings are reasonable | kubectl get hpa,scaledobject,vpa -A |
| Node scaling | User pools have CA or NAP enabled; max-count/limits match quota and subnet IPs; the profile matches the load pattern; VMSS is not edited by hand | az aks show --query autoScalerProfile, kubectl get nodepools |
| Cost | Interruptible workloads run on Spot; idle pools can scale to 0; GPU pools have min 0 or a clear reason not to; consolidation is enabled | Cost analysis add-on, node utilization |
| Availability | ≥ 3 replicas, PDB maxUnavailable 1 + AlwaysAllow, cross-zone topology spread, ZRS storage; no PDB with ALLOWED=0 | kubectl get pdb -A |
| Observability | Enable control plane logs for cluster-autoscaler and node-auto-provisioning; alert on Pending Pods lasting over 10 minutes, unhealthy CA, and NodeClaim startup failures | Diagnostic settings and managed Prometheus control plane metrics |
Why: scaling problems are often combination problems
Each component usually works fine on its own. Incidents come from combinations. Small requests + HPA watching utilization → HPA does not scale out. HPA scales out + the pool hits max → Pods stay Pending. The pool is below max + insufficient quota → scale-out fails. Scaled up + no PDB → a full disruption during scale-down. A review has to follow this chain and check each link.
How: 10 common errors
| # | Error | Symptom | Fix |
|---|---|---|---|
| 1 | No requests, or requests far too small | Node CPU is maxed out but does not scale out; HPA shows <unknown> | Set requests (use VPA recommendations) |
| 2 | Requests far too large | Node utilization is low but Pods are Pending, and cost is high | Raise requests |
| 3 | max-count / NodePool limits too small | max node group size reached | Raise them, and check quota and IPs |
| 4 | vCPU quota or subnet IPs insufficient | Scale-out fails, node creation errors | Request quota; use Overlay; expand the subnet |
| 5 | PDB allows no disruption | No scale-down, upgrade stuck | maxUnavailable 1 + AlwaysAllow |
| 6 | A single large Pod exceeds the allocatable capacity of a single node in every pool | CA NotTriggerScaleUp | Larger-SKU pool or NAP |
| 7 | HPA and VPA both control CPU | Replicas and requests oscillate | VPA Off, or VPA manages memory only |
| 8 | Manually changing VMSS capacity or autoscaling in the MC_ resource group | Node count conflicts with CA, and state becomes inconsistent | Only use az aks / CA |
| 9 | Online services entirely on Spot, or Spot without a fallback | Service interrupted when Spot is reclaimed | Regular-pool baseline + fallback design |
| 10 | Scale-down too aggressive, or NAP budgets too loose | Frequent node and Pod moves, many cold starts | Raise unneeded-time, tighten budgets, use do-not-disrupt |
When: when to run a review
- Before a new service goes live, before a promotion or peak event, every quarter for cost review, and after each Kubernetes minor-version upgrade (add-on versions change too, for example KEDA 2.17 → 2.19 → 2.20).
Observability essentials
- CA metrics: use control plane metrics (preview) with Azure Monitor managed Prometheus. Enable the
controlplane-cluster-autoscalerscrape target, which is off by default, to getcluster_autoscaler_unschedulable_pods_count,cluster_autoscaler_unneeded_nodes_count,cluster_autoscaler_cluster_safe_to_autoscale, andcluster_autoscaler_scale_down_in_cooldown(details in Prometheus hour 3). - Logs: in diagnostic settings, enable the
cluster-autoscalerandnode-auto-provisioningcategories. KQL:AKSControlPlane | where Category == "cluster-autoscaler",AKSControlPlane | where Category == "karpenter-events". - Kubernetes events:
source=cluster-autoscaler,source=karpenter-events,reason=FailedScheduling.
Comparison with similar practices
| This hour's review checklist | Azure Well-Architected (AKS) | AKS Deployment Safeguards | |
|---|---|---|---|
| Format | Manual review + scripts | Architecture guidance and assessment | Enforced by Azure Policy (for example, requiring requests, or validating PDBs) |
| Timing | Before go-live and periodically | Design phase | At every deployment |
Architecture diagram: the four-layer chain of scaling
Flowchart: diagnostic order when a Pod has been Pending for more than 5 minutes
Interactive review scorer
Choose a preset cluster or check the items yourself. The scorer rates you across 6 dimensions and points out which common errors each gap can cause. The terminal below shows the matching check commands.
Review script: collect scaling information in one go
#!/usr/bin/env bash
# Usage: RG=rg-aks-lab CLUSTER=aks-lab ./scaling-review.sh
set -u
echo "== Node pools =="
az aks nodepool list -g "$RG" --cluster-name "$CLUSTER" \
--query "[].{name:name,mode:mode,vm:vmSize,os:osSku,zones:join(',',availabilityZones||['-']),prio:scaleSetPriority,auto:enableAutoScaling,min:minCount,max:maxCount,count:count,maxPods:maxPods}" -o table
echo "== CA profile / NAP mode / KEDA / VPA =="
az aks show -g "$RG" -n "$CLUSTER" --query "{profile:autoScalerProfile, nap:nodeProvisioningProfile.mode, keda:workloadAutoScalerProfile.keda.enabled, vpa:workloadAutoScalerProfile.verticalPodAutoscaler.enabled}" -o jsonc
echo "== Containers without requests =="
kubectl get pod -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}{"\t"}{range .spec.containers[*]}{.name}={.resources.requests.cpu}/{.resources.requests.memory};{end}{"\n"}{end}' \
| grep -E "=/;|=;|=/[0-9]" | grep -v "^kube-system" | head -20
echo "== HPA / ScaledObject / VPA =="
kubectl get hpa,scaledobject,vpa -A 2>/dev/null
echo "== PDBs that do not allow disruption =="
kubectl get pdb -A -o jsonpath='{range .items[?(@.status.disruptionsAllowed==0)]}{.metadata.namespace}/{.metadata.name}{"\n"}{end}'
echo "== Pending Pods =="
kubectl get pod -A --field-selector=status.phase=Pending
echo "== Recent scaling events =="
kubectl get events -A --field-selector source=cluster-autoscaler --sort-by=.lastTimestamp 2>/dev/null | tail -10
kubectl get events -A --field-selector source=karpenter-events --sort-by=.lastTimestamp 2>/dev/null | tail -10
echo "== Node requests allocation rate =="
kubectl describe nodes | grep -E "^Name:|^ cpu |^ memory " | paste - - - | awk '{print $2, "cpu", $4, $5, "mem", $9, $10}'
== Node pools == Name Mode Vm Os Zones Prio Auto Min Max Count MaxPods --------- ------ --------------- ---------- ----- ------- ----- --- --- ----- ------- syspool System Standard_D4s_v5 AzureLinux 1,2,3 Regular False 3 110 userpool User Standard_D4s_v5 AzureLinux 1,2,3 Regular True 3 9 3 110 spotpool User Standard_D8as_v5 AzureLinux - Spot True 0 6 0 110 == PDBs that do not allow disruption == legacy/billing-api
workloadAutoScalerProfile.verticalPodAutoscaler.enabled is the ARM field path for VPA (follow the actual output of az aks show). The script is read-only and does not modify any resources.
KQL: scaling activity in the last 24 hours
AKSControlPlane
| where TimeGenerated > ago(24h)
| where Category in ("cluster-autoscaler", "karpenter-events")
| where Message has_any ("Scale-up", "scale-up", "ScaleDown", "Launched", "Disrupting")
| project TimeGenerated, Category, Message
| order by TimeGenerated desc
Lab 8: Run a scaling review on aks-lab (about 10 minutes, no additional cost)
chmod +x scaling-review.sh && RG=$RG CLUSTER=$CLUSTER ./scaling-review.sh | tee review-$(date +%F).txtKubePodInventory | where PodStatus == "Pending" | summarize count() by bin(TimeGenerated, 5m) (Container Insights) to create a log alert for 'Pending Pods lasting 10 minutes'.Case 1: The pre-Black Friday scaling review found 4 risks
Problem: the review covered 40 services. 7 had no requests, 3 PDBs had ALLOWED=0, the userpool max was 20 but the vCPU quota only allowed 14 VMs, and HPA max was commonly 10. Approach: fix the checklist items, request quota in advance, and load-test the end-to-end time to scale from 3 to 60 replicas (6 minutes). Then use a KEDA cron to warm up one hour early. Limitation: quota requests can take several days, so run the review early.
Case 2: Cost review: requests are 4 times actual usage
Problem: a 30-node cluster has average CPU usage of 12%, and its requests allocation rate is 85%. Approach: use VPA Off to collect two weeks of recommendations, lower requests in batches, set CA expander=least-waste, and move batch jobs to Spot. The node count dropped to 14. Limitation: after lowering requests, watch P99 latency and throttling (K8s hour 2).
Case 3: Review after migrating to NAP
Problem: after the move to NAP, there were about 40 consolidations per day, and some Java services cold-started frequently. Approach: adding karpenter.sh/do-not-disrupt to these services is not a good option, because it blocks all optimization. Instead, set the NodePool budget to 0 during working hours and 20% at night, and configure a suitable startupProbe and PDB for the Java services.
Interactive troubleshooting decision tree: scaling problems
Start from the symptom, select what you see step by step, and get the diagnosis and commands.
Supplement: frequently seen errors
pod didn't trigger scale-up: 3 node(s) didn't match Pod's node affinity/selector, 2 max node group size reached
Cause: a combination problem. Some pool labels do not match, and the matching pool has reached its limit.
Fix: raise max-count on the matching pool or correct the nodeSelector, and confirm quota.
HPA ScalingLimited: the desired replica count is more than the maximum replica count
Cause: HPA has reached maxReplicas.
kubectl -n myapp describe hpa myapp | sed -n '/Conditions/,$p'
Fix: decide whether a higher max is needed (and check node-level capacity at the same time), or improve single-replica performance.
The node count keeps flipping between two values (scaling every 10–15 minutes)
Cause: periodic load with scale-down parameters that are too short, or HPA scales down so quickly that CA decides the node is idle.
Fix: raise scale-down-unneeded-time and scale-down-delay-after-add, and the HPA scaleDown stabilization window. For NAP, tighten the budgets or switch to WhenEmpty.
1. Use one command to view the cluster's CA profile, NAP mode, and KEDA status.
az aks show -g $RG -n $CLUSTER --query "{profile:autoScalerProfile, nap:nodeProvisioningProfile.mode, keda:workloadAutoScalerProfile.keda.enabled}" -o jsonc2. List all Pending Pods and the first scheduling failure reason for each.
kubectl get events -A --field-selector reason=FailedScheduling -o custom-columns=NS:.involvedObject.namespace,POD:.involvedObject.name,MSG:.message --sort-by=.lastTimestamp | tail -20
A team reports that cluster autoscaling is broken: the HPA shows 30/30 replicas, and 12 of them have been Pending for 20 minutes. The CA events show TriggeredScaleUp, but the node count has not gone up. How do you troubleshoot this?
The CA has already decided to scale up, so the problem is on the Azure side. ① Check whether the pool is in backoff with cluster-autoscaler-status. ② Check the VMSS activity log for the node resource group, or the status error from az aks nodepool show: quota (QuotaExceeded), zonal capacity (ZonalAllocationFailed), subnet IPs (Node Subnet mode), or a policy denial (Azure Policy blocks the SKU). ③ The node was created but is not Ready (image pull, CNI, or outbound traffic blocked by a firewall; see hours 2 and 7). Fix the matching problem, and prepare a second pool with a similar SKU, or switch to NAP, to improve the success rate.
Verified instructional videos
Official documentation
- Cluster autoscaler: logs, status and metrics
- Control plane metrics (preview)
- Best practices for large clusters
Video storyboard (about 80 seconds)
This course file cannot generate a video or MP3 directly. A storyboard and narration script are provided, which you can hand to a video tool.
Visual: four boxes from left to right: resource declaration, Pod scaling, node scaling, disruption protection.
Narration: Scaling is a chain. When one link fails, the next one looks broken.
Visual: a review checklist is ticked item by item, and red items pop up: "PDB allows zero disruptions" and "node pool maximum is too small".
Narration: Before go-live, review six dimensions: capacity, Pod scaling, node scaling, cost, availability and observability.
Visual: the troubleshooting tree expands from "Pod Pending" to "quota insufficient".
Narration: When something goes wrong, check the scheduler events first, then the autoscaler events and status, and finally check Azure quota, capacity and subnets.
Command cheat sheet
Node pools
az aks nodepool list -g $RG --cluster-name $CLUSTER -o table az aks nodepool add -g $RG --cluster-name $CLUSTER -n userpool \ --mode User --node-vm-size Standard_D4s_v5 --os-sku AzureLinux \ --zones 1 2 3 --max-pods 110 --labels workload=general az aks nodepool add ... --mode System --node-taints CriticalAddonsOnly=true:NoSchedule az aks nodepool update ... --mode User|System az aks nodepool update ... --os-sku Ubuntu|AzureLinux # rebuild the image in place az aks nodepool delete -g $RG --cluster-name $CLUSTER -n NAME --no-wait az aks list-vm-skus -l $LOC --size Standard_D4s_v5 --all -o table az vm list-usage -l $LOC -o table
Cluster Autoscaler
az aks nodepool update ... --enable-cluster-autoscaler --min-count 3 --max-count 9 az aks nodepool update ... --update-cluster-autoscaler --min-count 3 --max-count 12 az aks nodepool update ... --disable-cluster-autoscaler az aks update -g $RG -n $CLUSTER --cluster-autoscaler-profile \ scale-down-unneeded-time=15m,expander=least-waste,balance-similar-node-groups=true az aks update -g $RG -n $CLUSTER --cluster-autoscaler-profile "" # reset kubectl get cm -n kube-system cluster-autoscaler-status -o yaml kubectl get events -A --field-selector source=cluster-autoscaler kubectl annotate node N cluster-autoscaler.kubernetes.io/scale-down-disabled=true # Pod annotation: cluster-autoscaler.kubernetes.io/safe-to-evict: "false"
NAP (Karpenter)
az aks create ... --node-provisioning-mode Auto \ --network-plugin azure --network-plugin-mode overlay --network-dataplane cilium az aks update ... --node-provisioning-mode Auto [--node-provisioning-default-pools None] az aks update ... --node-provisioning-mode Manual # drain the NAP nodes first kubectl get nodepools,aksnodeclasses,nodeclaims kubectl get nodes -l karpenter.sh/nodepool -L node.kubernetes.io/instance-type,karpenter.sh/capacity-type kubectl get events -A --field-selector source=karpenter-events # Pod/node annotation: karpenter.sh/do-not-disrupt: "true"
HPA / KEDA / VPA
kubectl autoscale deploy myapp -n myapp --cpu-percent=60 --min=3 --max=30 az aks update -g $RG -n $CLUSTER --enable-keda # --disable-keda az aks show -g $RG -n $CLUSTER --query workloadAutoScalerProfile.keda.enabled kubectl get scaledobject,hpa -A az aks update -g $RG -n $CLUSTER --enable-vpa # --disable-vpa kubectl describe vpa NAME -n NS # VPA updateMode: Off | Initial | Recreate | InPlaceOrRecreate (1.34+)
Spot
az aks nodepool add -g $RG --cluster-name $CLUSTER -n spotpool \ --priority Spot --eviction-policy Delete --spot-max-price -1 \ --enable-cluster-autoscaler --min-count 0 --max-count 6 # Automatic label: kubernetes.azure.com/scalesetpriority=spot # Automatic taint: kubernetes.azure.com/scalesetpriority=spot:NoSchedule az vmss simulate-eviction -g $NRG -n $VMSS --instance-id 0
GPU
az aks nodepool add ... -n gpupool --node-vm-size Standard_NC4as_T4_v3 \ --node-taints sku=gpu:NoSchedule --enable-managed-gpu=true \ --enable-cluster-autoscaler --min-count 0 --max-count 2 az aks nodepool add ... --enable-managed-gpu=false --gpu-driver None # BYO az aks nodepool show ... -n gpupool --query gpuProfile kubectl get nodes -o custom-columns='N:.metadata.name,GPU:.status.allocatable.nvidia\.com/gpu'
Availability
kubectl get pdb -A
kubectl get pdb -A -o jsonpath='{range .items[?(@.status.disruptionsAllowed==0)]}{.metadata.namespace}/{.metadata.name}{"\n"}{end}'
kubectl get nodes -L topology.kubernetes.io/zone,agentpool
kubectl cordon NODE; kubectl drain NODE --ignore-daemonsets --delete-emptydir-data --timeout=5m
kubectl uncordon NODECleanup
az aks nodepool delete -g $RG --cluster-name $CLUSTER -n gpupool --no-wait az aks nodepool delete -g $RG --cluster-name $CLUSTER -n spotpool --no-wait az aks delete -g $RG -n aks-lab-nap --yes --no-wait az aks stop -g $RG -n $CLUSTER # end of today az group delete -n $RG --yes --no-wait # end of the whole course
Quick troubleshooting table
| Symptom / error | Most likely cause | First command | Module |
|---|---|---|---|
| FailedScheduling Insufficient cpu, but no TriggeredScaleUp | Pool does not have CA enabled / at max / Pod too large / taint | kubectl get events --field-selector reason=NotTriggerScaleUp -A | 2 |
| TriggeredScaleUp but the node never appears | Quota, zonal capacity, subnet IPs, policy | kubectl get cm -n kube-system cluster-autoscaler-status -o yaml | 2, 8 |
| Node is idle but not scaling down | PDB=0, bare Pods, kube-system Pods, annotations | kubectl get pdb -A | 2, 7 |
| NAP does not create nodes | NodePool requirements do not intersect / limits exhausted / taint | kubectl get events -A --field-selector source=karpenter-events | 3 |
| HPA <unknown> | No CPU requests | kubectl describe hpa | 4 |
| ScaledObject READY False | scaler connection/authentication | kubectl -n kube-system logs deploy/keda-operator | 4 |
| Spot pool stays at 0 nodes | CA not enabled / no Spot capacity | az aks nodepool show -n spotpool | 5 |
| Insufficient nvidia.com/gpu | No device plugin (driver-only mode) | kubectl get node -o jsonpath='{.status.allocatable}' | 6 |
| Drain stuck: violates disruption budget | PDB too strict | kubectl get pdb -A | 7 |
Recommended configuration snippets
Online service baseline (Deployment snippet + PDB)
spec:
replicas: 3
template:
spec:
topologySpreadConstraints:
- { maxSkew: 1, topologyKey: topology.kubernetes.io/zone, whenUnsatisfiable: DoNotSchedule, nodeTaintsPolicy: Honor, labelSelector: { matchLabels: { app: myapp } }, matchLabelKeys: [pod-template-hash] }
- { maxSkew: 1, topologyKey: kubernetes.io/hostname, whenUnsatisfiable: ScheduleAnyway, labelSelector: { matchLabels: { app: myapp } }, matchLabelKeys: [pod-template-hash] }
containers:
- name: myapp
resources: { requests: { cpu: 250m, memory: 256Mi }, limits: { memory: 512Mi } }
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: myapp }
spec: { maxUnavailable: 1, unhealthyPodEvictionPolicy: AlwaysAllow, selector: { matchLabels: { app: myapp } } }NAP general-purpose NodePool
apiVersion: karpenter.sh/v1
kind: NodePool
metadata: { name: general }
spec:
limits: { cpu: "200", memory: 800Gi }
disruption:
consolidationPolicy: WhenEmptyOrUnderutilized
budgets:
- nodes: "10%"
- { nodes: "0", schedule: "0 13 * * 1-5", duration: 8h }
template:
spec:
expireAfter: Never
requirements:
- { key: karpenter.azure.com/sku-family, operator: In, values: ["D", "E"] }
- { key: karpenter.sh/capacity-type, operator: In, values: ["on-demand"] }
- { key: kubernetes.io/arch, operator: In, values: ["amd64"] }
nodeClassRef: { group: karpenter.azure.com, kind: AKSNodeClass, name: default }Capstone lab + final quiz
rg-aks-lab / aks-lab / the namespace myapp.az aks nodepool list -g $RG --cluster-name $CLUSTER --query "[].{n:name,mode:mode,os:osSku,zones:availabilityZones,auto:enableAutoScaling,min:minCount,max:maxCount,taints:nodeTaints}" -o jsoncaz aks update -g $RG -n $CLUSTER --cluster-autoscaler-profile scale-down-unneeded-time=15m,scale-down-delay-after-add=15m,balance-similar-node-groups=true,expander=least-wastemyapp-cron.yaml (cron + CPU 60%); apply the PDB and topology spread (see the Commands tab in Module 7).
kubectl -n myapp delete hpa myapp --ignore-not-found kubectl apply -f myapp-cron.yaml kubectl -n myapp get scaledobject,hpa,pdb
myapp-worker (replacing the nodeSelector), then apply worker-scaledobject.yaml.
kubectl -n myapp patch deploy myapp-worker --type json -p '[{"op":"remove","path":"/spec/template/spec/nodeSelector"}]'
kubectl -n myapp patch deploy myapp-worker --type merge -p '{"spec":{"template":{"spec":{"tolerations":[{"key":"kubernetes.azure.com/scalesetpriority","operator":"Equal","value":"spot","effect":"NoSchedule"}],"affinity":{"nodeAffinity":{"requiredDuringSchedulingIgnoredDuringExecution":{"nodeSelectorTerms":[{"matchExpressions":[{"key":"kubernetes.azure.com/scalesetpriority","operator":"In","values":["spot"]}]}]}}}}}}}'
kubectl apply -f worker-scaledobject.yamlkubectl -n myapp exec deploy/redis -- sh -c 'for i in $(seq 1 200); do redis-cli LPUSH jobs j$i >/dev/null; done' kubectl get nodes -L agentpool,kubernetes.azure.com/scalesetpriority -w
scaling-review.sh and score it in the scorer. Stop the load test and delete the load and probe Pods. End of today: az aks stop -g $RG -n $CLUSTER (if you created aks-lab-nap, delete it).Open-ended self-check (answer first, then expand the reference answer)
1. What are the criteria CA uses to decide that scale-up is needed and that scale-down is allowed? Why is neither related to actual CPU usage?
Scale up: there are Pods that cannot be scheduled because of resources or constraints, and a node template in some pool can fit them after simulation. Scale down: node requests utilization < threshold (0.5) for a sustained unneeded-time, and all Pods can be moved without being blocked by PDBs or other rules. Both are based on requests and scheduling simulation, because the scheduler itself only looks at requests.
2. What are the three fundamental differences between NAP and CA? What are NAP's limitations?
Differences: ① NAP picks the SKU directly (NodePool requirements ∩ Pod constraints, by price) and does not depend on pre-built pools; ② its unit is the NodeClaim (a single VM); ③ it actively consolidates (deletes or replaces with smaller nodes) and handles drift. Limitations: kubenet, Calico, and dynamic Pod Subnet allocation are not supported, and neither is IPv6; Windows is outside formal support; service principals are not supported; the cluster cannot be stopped; the outbound type cannot be changed after creation.
3. In the KEDA add-on, which component handles 0→1 and which handles 1→N?
0↔1 is handled by keda-operator, which changes the replica count directly based on the scaler's activation conditions. 1↔N is handled by the HPA that KEDA generates (keda-hpa-*), which calculates from external metrics served by keda-operator-metrics-apiserver.
4. Why can't a PDB protect against Spot eviction? What keeps Spot workloads reliable?
Spot eviction means Azure infrastructure deletes the VM. It does not call the Kubernetes Eviction API. Reliability depends on replica redundancy, task retries (backoffLimitPerIndex), checkpoints, and a fallback to regular pools (preferred affinity, priority expander, or NAP capacity-type).
5. A GPU node pool is Ready after creation, but GPU Pods stay Pending (Insufficient nvidia.com/gpu). What could be the cause?
The default driver-only configuration has no device plugin, so the node does not advertise nvidia.com/gpu. Or the device plugin does not tolerate the sku=gpu taint, or the GPUs are already fully allocated. Fix: deploy the device plugin, or create a new pool with --enable-managed-gpu=true.
6. Design question: a service has a 5-minute traffic peak every 15 minutes. How would you configure HPA and CA so the nodes don't scale up, scale down, and scale up again?
Set the HPA scaleDown stabilization window to at least 10 minutes, or use KEDA cron to cover the peak hours. Set CA scale-down-unneeded-time and scale-down-delay-after-add to around 20 minutes, so the nodes stay up between the two peaks. If cost is a concern, use a separate NAP NodePool for this service with consolidateAfter (WhenEmpty) set to 20 minutes, so other pools are not affected.
Final quiz (12 questions, covering all modules)
Sources and versions
| Topic | Verification result | Sources (accessed 2026-11-15) |
|---|---|---|
| Supported versions and components | GA: 1.34 (EOL 2026-11), 1.35, 1.36, 1.37 (GA 2026-10); 1.38 preview 2026-11. Component table: 1.35 KEDA 2.17.2 / VPA 1.5.1 / Karpenter 1.7.0-aks / CA v1.35.0-aks-2; 1.36 KEDA 2.19.0 / VPA 1.6.0 / Karpenter 1.12.2-aks / CA v1.35.0-aks-4; 1.37 KEDA 2.20.2 / VPA 1.7.1 | Supported Kubernetes versions (updated 2026-10-21) |
| Cluster Autoscaler | Enable, update and disable commands; profile is cluster-level; all parameter defaults (scan-interval 10s, delay-after-add 10m, delay-after-failure 3m, unneeded 10m, unready 20m, threshold 0.5, max-graceful 600s, expander random, skip-system-pods true, skip-local-storage false, max-empty-bulk-delete 10, new-pod-scale-up-delay 0s, unready 45%/3, max-node-provision-time 15m); aggressive and burst reference profiles; ProvisioningRequest requires 1.33+; log categories and metrics; manual edits to the VMSS are not allowed | Use the cluster autoscaler in AKS (updated 2026-11-02) |
| NAP | Built on Karpenter + karpenter-provider-azure; AKS Automatic pre-provisioning; Standard uses --node-provisioning-mode Auto; CLI ≥ 2.76.0; limitations: Windows node pools, IPv6 and service principals are not supported, the cluster cannot be stopped, the outbound type cannot be changed, and a custom VNet requires Standard LB; default NodePools default and system-surge; --node-provisioning-default-pools Auto|None; disable steps; event source karpenter-events | NAP overview · Enable/disable NAP (updated 2026-11-05) |
| NAP NodePool / AKSNodeClass | NodePool karpenter.sh/v1, AKSNodeClass karpenter.azure.com/v1beta1; default pool YAML (budgets 30%, expireAfter Never, sku-family D, on-demand, Cilium startup taint); SKU selector table; Spot is preferred when both Spot and on-demand are allowed; weight 1–100; limits; static pool replicas; imageFamily Ubuntu/AzureLinux/AzureContainerLinux (Windows in preview); osDiskSizeGB default 128, minimum 30; maxPods default 250 with Overlay | Configure NodePools · AKSNodeClass (updated 2026-11-11) |
| NAP disruption and networking | consolidationPolicy WhenEmpty / WhenEmptyOrUnderutilized; default budgets 10%; expiration is a forced method and is not limited by budgets; terminationGracePeriod bypasses PDBs and do-not-disrupt; networking: Overlay and Node Subnet are supported, while dynamic Pod Subnet, kubenet and Calico are not; Cilium recommended; dual-stack in preview | Disruption · Networking |
| KEDA add-on | --enable-keda / --disable-keda; verify workloadAutoScalerProfile.keda.enabled; each of the three components runs 2 replicas; the version is determined by the Kubernetes version; Helm values cannot be modified; KEDA 2.15+ removes pod identity; for OOM, use VPA InPlaceOrRecreate | Install the KEDA add-on (updated 2026-05-13) |
| VPA add-on | --enable-vpa (CLI ≥ 2.52.0); Auto has been deprecated since VPA 1.4.0 (AKS 1.34+) and is equivalent to Recreate; InPlaceOrRecreate is available on AKS 1.34+; from 1.34 the components default to 2 replicas; controlledValues defaults to RequestsAndLimits | Use the VPA in AKS |
| Spot node pools | Commands and parameters; cannot be the default pool; priority, max price and eviction cannot be changed; automatic labels and taints; upgrades only cordon, with no drain and no surge; Deallocate consumes quota; CA recommended | Add an Azure Spot node pool |
| GPU | Managed GPU: --enable-managed-gpu=true (CLI ≥ 2.85.0) installs the driver, device plugin, DCGM exporter, and NPD health signals; the default is driver-only; BYO with --gpu-driver None; MIG strategy; fields are immutable; minimum recommended SKU NC4as_T4_v3; --skip-gpu-driver-install retired 2025-08-14; Flatcar and OS Guard do not support NVIDIA GPUs | AKS-managed GPU nodes (updated 2026-11-11) · Use GPUs on AKS |
| Node pools, quota and reservations | System pool limits (Linux, 3 recommended with at least 2 nodes, at least 4 vCPU/4 GB, no B-series, maxPods ≥30); 1000 nodes per pool, 100 pools, 5000 nodes per cluster; CPU reservation tiers and the memory formula min(20MB×maxPods+50MB, 25%) + 100Mi | System pools · Quotas · Resource reservations |
| OS SKU | Ubuntu: 1.25–1.34 is 22.04, 1.35+ is 24.04; AzureLinux: 1.32+ is 3.0; AzureLinux3 supports 1.28–1.36; Ubuntu2404 supports 1.32–1.38; Azure Linux 2.0 support ended 2025-11-30 and its images will be deleted 2026-10-31; Ubuntu 22.04 is supported until 2027-06-30; Linux pools can be migrated in place with nodepool update --os-sku | Upgrade OS version · Use Azure Linux |
| Availability zones | zone-spanning / zone-aligned / regional; availability zones cannot be changed after creation; for zone-aligned, balance-similar-node-groups is recommended; 1.29+ defaults to ZRS managed disks; Basic LB retired 2025-09-30; --zones auto in preview | Configure availability zones |
| PDB / topology spread / HPA | Upstream Kubernetes semantics | PDB · Topology spread · HPA |
Video verification notes
The following videos were verified on 2026-11-15 through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json) for their titles and channels: Azure Kubernetes Service (AKS) official channel, “Azure Linux for AKS - A stable and performant node OS” (yisak-hY4aY), “AKS Automatic Scaling Deep Dive: Azure Kubernetes Service” (A7nUE_qlivQ), “AKS Node Auto Provisioning (NAP) - Feature Overview (Azure Kubernetes Service)” (1BCsuy35JKg), “Node Auto Provisioning with Wilson Darko: (NAP) AKS Troubleshooting Series: Azure Kubernetes Service” (LVgAolj3QGA); Microsoft Azure, “Azure Linux with Azure Kubernetes Service (AKS) | Azure Friday” (AKjgrveI9ww); Anton Putra, “Kubernetes Autoscaling: HPA vs. VPA vs. Keda vs. CA vs. Karpenter vs. Fargate” (hsJ2qtwoWZw); Programming with Wolfgang, “Karpenter for Azure - Hands on with AKS Node Auto Provisioning” (e2oE_wczdw0); DevOps & AI Toolkit, “KEDA: Kubernetes Event-Driven Autoscaling” (3lcaawKAv6s), “Scaling Explained Through Kubernetes HPA, VPA, KEDA & Cluster Autoscaler” (HQY2jgSN6pA), “GPUs in Kubernetes for AI Workloads” (zuRKdveFuZ4); That DevOps Guy, “Understanding CPU & Memory with the Kubernetes Vertical Pod Autoscaler” (jcHQ5SKKTLM); Lukonde Mwila, “Pod Topology Spread Constraints in Kubernetes” (hv8lHqRZFJA); Drewbernetes, “Kubernetes Pod Disruption Budgets | How to keep your workloads online during planned maintenance” (keuOGPl7vDo). oEmbed does not return duration or publish date, so durations are not listed on the cards. No official feature video was found for Spot node pools or AKS-managed GPUs, so storyboard scripts are provided instead. Community videos may have been recorded before the current version; commands and defaults follow this hour and the official docs.
Voice narration notes
The "Voice" tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time, with English terms pronounced in en-US. The result depends on the English voices installed in the operating system (for example, Microsoft Aria on Windows or Samantha on macOS). This course file cannot call a TTS service from the environment where it was generated, so no MP3 is embedded. If you need offline audio, give the narration script to a TTS service such as Azure AI Speech to generate it.
Known limitations
- The commands in this course file were not actually run in the generation environment. All node names, VMSS suffixes, IPs, times, image version numbers, NodeClaim names, prices and counts in the "expected output" are example values; your own environment is the reference.
- Costs are rough hourly example estimates (canadacentral, on the order of Linux on-demand retail prices). They do not include the Standard tier control plane fee, disks, traffic or taxes. Refer to the Azure pricing calculator and the retail prices API.
- The official docs contain two inconsistencies, which this hour handles conservatively. ① The NAP AKSNodeClass page says Ubuntu 24.04 is the default for 1.34+, while the OS version page says 1.35+. This hour follows the OS version page (1.35+). ② The NAP disruption page comments that
consolidateAftercan currently only be set with WhenEmpty, but the default pool and the managed GPU example also set it under WhenEmptyOrUnderutilized. This hour keeps the field in its examples and notes that CRD validation is the reference. The disruption page example putsexpireAfterunderspec.disruption; this hour follows karpenter.sh/v1 and the default pool and puts it underspec.template.spec. - The official list of current limitations does not explicitly describe how NAP and Cluster Autoscaler coexist in the same cluster. This hour recommends using taints and labels to assign workloads to one or the other.
- The full usage of the CA priority expander ConfigMap on AKS-managed CA is not documented in the AKS docs. This hour presents it only as an optional approach and recommends verifying it first. Using
nvidia.com/gpuin NodePoollimitsis a general Karpenter capability, and no example was found in the AKS docs. - The raw format of the
cluster-autoscaler-statusConfigMap and of Karpenter events changes between versions. Some error messages in the troubleshooting summary are general descriptions (they start with "Symptom:"). - The times, price ordering and utilization in the animation are illustrative values that explain the mechanism. They are not the exact output of the CA or Karpenter algorithms.