AKS Hour 4: Scaling and Node Management

From “how to design node pools” to “how a Pending Pod becomes a new VM”: Cluster Autoscaler, NAP (Karpenter), HPA/KEDA/VPA, Spot, GPU, and availability
AKS 1.35 / 1.36 / 1.37NAP is GA (Karpenter 1.12.x-aks on 1.36)KEDA 2.19 / 2.20 add-onVPA add-on 1.6 / 1.7Verified against learn.microsoft.com · 2026-11-15
Overall learning goals
  • 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, using cluster-autoscaler-status and events.
  • Understand Node Auto Provisioning (NAP): AKS-managed Karpenter. It uses a NodePool (karpenter.sh/v1) and an AKSNodeClass (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, including InPlaceOrRecreate) 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

#TimeModuleCore contentAnimation / interactiveLab (rg-aks-lab)
0Before classWarm-up: capacity planningReuse aks-lab and myapp, check node pools, calculate total requestsCapacity planning calculatorExport current node pool manifests
100–06Node pool design: VM sizes, OS, and availability zonessystem/user pools, VM families, maxPods and allocatable, Azure Linux 3.0, zone-spanning vs zone-aligned, immutable propertiesNode pool designer (allocatable calculation)Add an Azure Linux user pool (3 availability zones)
206–13Cluster AutoscalerScale-up/scale-down algorithm, simulated scheduling, full profile parameters, expanders, balance-similar-node-groups, logs and status ConfigMapCA scale-down timer simulatorTrigger scale-up with a load test, then adjust the profile and watch scale-down
313–21Node Auto Provisioning (Karpenter)NodePool / AKSNodeClass / NodeClaim, SKU selectors, limits/weight, consolidation, drift, budgets, limitationsCore animation: how Pending Pods drive the CA vs NAP scale-up decisionCustom NodePool on aks-lab-nap
421–28HPA, KEDA add-on, and VPAHPA formula and behavior, KEDA ScaledObject and scale to zero, VPA modes and InPlaceOrRecreate, conflicts among the threeHPA formula + KEDA queue scaling simulatormyapp HPA + KEDA cron scaling + VPA recommendations
528–35Spot node pools and cost optimizationSpot pricing and eviction, automatic taints, tolerations + affinity, fallback to regular pools, priority expander, cost leversSpot eviction and fallback simulatorAdd a Spot pool and run an interruptible Job
635–42GPU and dedicated workloadsAKS-managed GPU (driver + device plugin + DCGM), driver only, BYO (GPU Operator), MIG, taint isolation, scale to zeroGPU scheduling chain animation(Optional, high cost) T4 GPU pool + nvidia-smi
742–50PDBs, topology spread, and zone redundancyPDBs and the Eviction API, topologySpread across zones and nodes, ZRS disks, zone failure drillAvailability zone failure simulatormyapp across 3 zones + PDB + drain drill
850–60Scaling review and common mistakesReview checklist, 10 common mistakes, metrics and alerts, troubleshooting decision treeScaling review scorer + troubleshooting treeRun a review on aks-lab
—After classCheat sheet · Capstone labBuild an elastic, cost-efficient, zone-failure-resilient node and pod scaling setup for myappFinal quiz (12 questions)Capstone lab

Knowledge coverage matrix

Target skillM1M2M3M4M5M6M7M8Key commandsLab
Design a node pool (size, OS, maxPods, availability zones)✓·✓·✓✓✓✓az aks nodepool addAzure Linux pool
Calculate allocatable and capacity✓✓·····✓kubectl describe nodeModule 0/1
Enable and tune Cluster Autoscaler·✓··✓✓·✓--cluster-autoscaler-profileScale up / scale down
Use NAP (NodePool/AKSNodeClass)··✓·✓✓·✓--node-provisioning-mode Autoaks-lab-nap
Pod horizontal, vertical, and event-driven scaling···✓···✓kubectl autoscale, ScaledObject, VPAmyapp HPA/KEDA
Spot and cost optimization·✓✓·✓··✓--priority SpotSpot Job
GPU node pool··✓··✓··--enable-managed-gpunvidia-smi
PDB / topology spread / zone redundancy✓✓✓···✓✓kubectl get pdb, draindrain drill
Scaling troubleshooting·✓✓✓✓✓✓✓events, cluster-autoscaler-status, nodeclaimsTroubleshooting tree

What this hour leaves out (and where to learn it)

TopicWhy it's not in this hourWhere to learn it
requests/limits, QoS, scheduler Filter/Score, general affinity and taint semanticsGeneral Kubernetes concepts that this hour uses directlyK8s Hour 2
General principles of HPA / VPA and metrics-serverThis hour only covers AKS add-ons and how they link to nodesK8s Hour 6 (autoscaling)
Node pool upgrades, surge, node images, and maintenance windowsBelongs to upgrades and operationsAKS Hour 6
Subnet IP exhaustion and SNAT port exhaustion effects on scale-upBelongs to deep troubleshootingAKS Hour 2 (networking) · Hour 7
Deploying myapp with Helm, managed Prometheus metrics collectionTool details are covered in other coursesHelm Hour 3 · Prometheus Hour 3
KAITO, DRA, Kueue + ProvisioningRequest, and other AI batch schedulingBeyond 1 hourThe ProvisioningRequest section of the CA docs

How to use this course

10 pages per module
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.
Progress
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).
English voice
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.
Version notesThis hour follows the AKS docs as of 2026-11-15. Supported GA versions are 1.34 (end of life at the end of 2026-11), 1.35, 1.36, and 1.37 (GA in 2026-10). Labs default to 1.36. According to the AKS component table, 1.36 ships KEDA 2.19.0, VPA 1.6.0, and Karpenter 1.12.2-aks; 1.37 ships KEDA 2.20.2 and VPA 1.7.1. CA versions are managed by AKS and follow the Kubernetes version. --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.
PrerequisitesThis hour assumes you have completed AKS Hour 1 (cluster 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)

Confirm that aks-lab and myapp are available, take inventory of node pools and total requests, and answer on paper first: how many nodes do you need, and how big should they be?
Before class ≈ 10 minReuses resources from hours 1–3
Prerequisites
  • Your subscription has the resource group rg-aks-lab (canadacentral), the cluster aks-lab (Standard tier, Azure CNI Overlay), and ACR acraks<suffix>. The namespace myapp runs myapp (Flask + gunicorn, port 5000, /healthz) and Redis.
  • Locally: Azure CLI ≥ 2.85 (--enable-managed-gpu needs 2.85; NAP needs ≥ 2.76; --gpu-driver needs ≥ 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
Costs and cleanup2 × Standard_D4s_v5 nodes cost about 0.4 USD/hour (example estimate), plus the Standard tier control plane fee (see hour 1). When you are not using it today: 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.

Environment self-check list

Module 1 · Node pool design: VM sizes, OS, and availability zones

00:00 – 06:00 · The node pool is the basic unit of AKS scaling: one pool = one VMSS = one VM size + one set of labels and taints + one set of availability zones
6 minAzure Linux 3.0 GAAvailability zones GA--zones auto preview★★★★★
Learning goals
  • 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-pods affects 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.
Prerequisites: requests, taints, and tolerations from K8s hour 2; node resource groups from AKS hour 1. Importance: ★★★★★ (all later scaling mechanisms work per node pool)

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)
PurposeCritical system pods such as CoreDNS, metrics-server, konnectivity, and CSI controllersBusiness workloads
OSLinux only (Ubuntu / Azure Linux)Linux or Windows
Node countAt 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 / taintsAutomatic kubernetes.azure.com/mode: system; adding CriticalAddonsOnly=true:NoSchedule is recommendedkubernetes.azure.com/mode: user
CountAt least 1 per clusterUp 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 familyCharacteristicsTypical use
Dsv5 / Ddsv5 / Dasv5 / Dpsv6 (Arm64)General purpose, vCPU:memory = 1:4Most web and API workloads (myapp)
Esv5 / Edsv5Memory optimized, 1:8Caches, large JVM heaps, database proxies
Fsv2Compute optimized, 1:2CPU-intensive batch work, encoding
Lsv3Local NVMe storage optimizedLocal-disk scenarios such as Kafka and Elasticsearch
NC / ND / NV (NVIDIA)GPU; AKS minimum recommendation Standard_NC4as_T4_v3Inference, 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-skuBehaviorRecommendation
UbuntuPicks the OS version automatically based on the K8s version: 1.25–1.34 uses 22.04, 1.35+ uses 24.04Default choice; the OS follows automatically when you upgrade K8s
AzureLinux1.27–1.31 uses Azure Linux 2.0, 1.32+ uses Azure Linux 3.0Smaller images and attack surface, Microsoft-built kernel; the default for AKS Automatic system pools
Ubuntu2404 / Ubuntu2204 / AzureLinux3Versioned 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 / FlatcarImmutable 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's balance-similar-node-groups in 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 poolEKS managed node groups / KarpenterGKE node pool
UnderlyingVMSS (NAP nodes are standalone VMs)Auto Scaling Group / EC2 FleetManaged Instance Group
Multiple sizesOne size per pool (NAP can use multiple SKUs)Node groups can have multiple instance types; Karpenter is dynamicOne type per pool (NAP is dynamic)
System pool conceptExplicit mode=SystemNone, uses labelsNone, uses labels
Common misconceptions ① "A system pool can scale to 0 to save money." No, it needs at least 2 nodes (3 recommended). ② "Just change the node pool's VM size." --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

AKS control plane (managed)API server · CA · Karpenter(NAP) Node resource group MC_rg-aks-lab_aks-lab_canadacentral Zone 1Zone 2Zone 3 syspool (mode=System) VMSS · 3 × D4s_v5 · AzureLinux · zones 1 2 3taint CriticalAddonsOnly=true:NoSchedule · CoreDNS / metrics-server / konnectivity userpool (mode=User) VMSS · D4s_v5 · CA min 3 / max 12 · zones 1 2 3 · maxPods 110myapp, redis, general services spotpool (priority=Spot) VMSS · D8as_v5 · CA 0–20taint kubernetes.azure.com/scalesetpriority=spot:NoSchedule · batch / interruptible gpupool · NC4as_T4_v3zone 1 · taint sku=gpu · CA 0–3 NAP node (standalone VM, not a VMSS)SKU and zone determined by NodePool/AKSNodeClass
Figure 1-1: one pool = one VMSS = one VM size. The system pool is isolated with a taint. Spot and GPU pools use their own taints. NAP nodes are standalone VMs.

Data flow diagram: how the resources of one D4s_v5 are divided

Memory 16 GiB (maxPods=110) kube-reserved 2.25GB allocatable ≈ 13.5 GiB (20MB×110+50MB=2250MB; eviction threshold 100Mi) Memory 16 GiB (maxPods=250) kube-reserved 4 GiB (capped at 25%) allocatable ≈ 11.9 GiB (20MB×250+50MB=5050MB > 25%) CPU 4 vCPU 140mallocatable 3860m (excludes DaemonSet requests, which take up some more)
Figure 1-2: maxPods directly determines memory reservation. CA, NAP, and the scheduler all look only at allocatable and requests.

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

CommandPurposeKey parameters / notes
az aks nodepool addAdd node pool--mode, --node-vm-size, --os-sku, --zones, --max-pods, --node-taints, --labels, --enable-cluster-autoscaler --min-count --max-count
az aks nodepool updateChange mutable properties--mode, --os-sku (migrate between Linux SKUs), --labels, --node-taints, autoscaler settings
az aks nodepool scaleSet node count manually (when CA is not enabled)--node-count
az aks nodepool deleteDelete node pool (cordons and drains nodes)A system pool must always keep at least one pool
az aks list-vm-skusCheck SKU availability and zone support in a region--location --size --all
az vm list-usageCheck vCPU quotaCommon 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)

Check SKU and quota:
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
Create userpool (command in the "Commands" tab, about 4–6 min), then check the node distribution:
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
Make myapp run only on userpool:
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-*.

Compare allocatable (Ubuntu maxPods 250 vs AzureLinux maxPods 110):
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).

Cleanup / keep: userpool is used in later modules. At the end of today, run az aks stop -g $RG -n $CLUSTER. To delete this pool: az aks nodepool delete -g $RG --cluster-name $CLUSTER -n userpool --no-wait.
Risk: before you delete a pool or change its mode, make sure at least one System pool remains. Deleting a node pool drains its nodes, and single-replica services without a PDB will have a brief outage.

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.

Command-line exercises
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 table
2. 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
Scenario analysis
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

▶
Azure Linux for AKS - A stable and performant node OS — Azure Kubernetes Service (AKS)
AKS official channel · English · Azure Linux as a node OS: design and advantages
▶
Azure Linux with Azure Kubernetes Service (AKS) | Azure Friday — Microsoft Azure
Azure Friday · English · recorded earlier, so versions and defaults follow this hour

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–90s
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.
Or score ≥ 70% on the quiz

Module 2 · Cluster Autoscaler

06:00 – 13:00 · It doesn't look at CPU utilization. It only looks at whether pods can't be scheduled for lack of resources, and at which node's requests are low enough to drain completely.
7 minGA · managed control planeprofile is cluster-wide★★★★★
Learning goals
  • 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 for scale-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-profile fluently, and read the cluster-autoscaler-status ConfigMap, events, and control plane logs.
Prerequisites: node pools from module 1; the K8s scheduler and PDBs. Importance: ★★★★★

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)

  1. List pods with PodScheduled=False, reason=Unschedulable. (new-pod-scale-up-delay can ignore pods that are too new.)
  2. 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.
  3. When several pools qualify, the expander chooses: random (AKS default), most-pods, least-waste, or priority (requires the cluster-autoscaler-priority-expander ConfigMap in kube-system; follow the official docs).
  4. Calculate how many nodes are needed, then call the Azure API to increase that VMSS's capacity. If balance-similar-node-groups is enabled, spread the increase across similar pools.
  5. 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

  1. 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-utilization determines whether DaemonSets count toward utilization.
  2. 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 with skip-nodes-with-local-storage=true; pod annotation cluster-autoscaler.kubernetes.io/safe-to-evict: "false"; node annotation cluster-autoscaler.kubernetes.io/scale-down-disabled: "true"; bare pods with no controller; or the node pool is already at min-count.
  3. The node must be marked "not needed" continuously for scale-down-unneeded-time (default 10 minutes), and more than scale-down-delay-after-add (default 10 minutes) must have passed since the last scale-up.
  4. Taint the node with ToBeDeletedByClusterAutoscaler, then evict its pods through the Eviction API (respects PDBs and waits up to max-graceful-termination-sec, default 600 seconds), then delete the VM. If the pool sets scaleDownMode: 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)

ParameterDefaultTuning direction
scan-interval10sRaise to 20–30s in large clusters to reduce API load
scale-down-delay-after-add10mRaise for bursty workloads to avoid scaling up and immediately back down
scale-down-delay-after-delete= scan-interval—
scale-down-delay-after-failure3m—
scale-down-unneeded-time10mFor 15-minute periodic jobs, set to 15–20m
scale-down-unready-time20m—
scale-down-utilization-threshold0.5Raise to 0.6–0.7 to save more (more aggressive)
ignore-daemonsets-utilizationfalseSet to true when DaemonSets are heavy
daemonset-eviction-for-empty-nodes / …-for-occupied-nodesfalse / trueAdjust when DaemonSets need a graceful exit (such as log flushing)
max-graceful-termination-sec600Should be ≥ the business terminationGracePeriodSeconds
balance-similar-node-groupsfalseSet to true when using one pool per zone
expanderrandomleast-waste saves money; priority favors Spot
skip-nodes-with-local-storagefalseSet to true if emptyDir holds data that must not be lost
skip-nodes-with-system-podstrue—
max-empty-bulk-delete10Speeds up reclaiming after large batch jobs
new-pod-scale-up-delay0sWhen submitting batch Jobs in bulk, set 10–30s so the scheduler can catch up first
max-total-unready-percentage / ok-total-unready-count45% / 3Once exceeded, CA stops acting (safety mechanism)
max-node-provision-time15m—

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 AutoscalerNAP (Karpenter)VMSS autoscaling (prohibited for AKS)
TriggerUnschedulable pods / low requests utilizationUnschedulable Pod / consolidation / driftVM metrics (CPU%)
Decision unitNode pool (VMSS)Individual NodeClaim (VM)VMSS
Chooses sizeNo, only the pool's size can be usedChooses from SKUs that meet the requirementsNo
Understands pod constraintsYes (simulated scheduling)YesNo
Common misconceptions ① "CA scales up when CPU usage hits 90%." No. CA doesn't look at utilization, only at Pending pods. If requests are set too low, a node's CPU can max out without triggering a scale-up. ② "The profile can be set per node pool." No, it's cluster-wide. ③ "Disabling CA deletes the extra nodes." No, after you disable it, the node count stays as it is. ④ "min-count is always respected." Yes. When external causes such as Spot eviction push the node count below min, CA actively restores min. ⑤ "Turning on autoscaling for the VMSS in the MC_ resource group works together with CA." No, the two will fight each other.

Architecture diagram: where CA sits in AKS

AKS managed control plane kube-apiserverPod / Node / PDB kube-schedulerMark Unschedulable cluster-autoscaler (one loop every 10s) ① list Unschedulable pods ② simulated scheduling against the template node (Filter plugins) ③ expander picks pool ④ scale-down candidate calculation (requests utilization + movability) Write state to ConfigMap kube-system/cluster-autoscaler-status Azure Resource Manager · Microsoft.ComputePUT VMSS sku.capacity +N / DELETE specific instance VMSS userpoolmin 3 · max 9D4s_v5 · zones 1 2 3New instance → kubelet registers VMSS spotpoolmin 0 · max 20Spot · D8as_v5After eviction, CA restores capacity
Figure 2-1: CA runs in the managed control plane and changes VMSS capacity through ARM. Only kube-scheduler ever binds pods.

Flowchart: the gates a node must pass before it can be scaled down

Utilization < 0.5?max(cpu,mem) requests Pods movable?Simulate scheduling onto other nodes No blocking conditions?PDB / annotation / system pod / local disk Sustained for 10m?unneeded-time Taint ToBeDeleted → evict≤600s → delete VMSS instance Any gate fails → timer resets and the node is kept (events and the status ConfigMap give the reason)Also required: at least scale-down-delay-after-add since the last scale-up; node pool count > min-count
Figure 2-2: scale-down must satisfy all conditions continuously. PDBs are the most common reason a node can't 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

CommandPurposeKey parameters
az aks nodepool update --enable-cluster-autoscalerEnable CA for a pool--min-count --max-count
az aks nodepool update --update-cluster-autoscalerChange min/maxCan be changed at any time
az aks nodepool update --disable-cluster-autoscalerDisable (does not delete nodes)Afterwards, you can use az aks nodepool scale
az aks update --cluster-autoscaler-profileSet cluster-wide profilek=v,k=v; "" resets to defaults
kubectl get cm -n kube-system cluster-autoscaler-statusCA health and per-pool status-o yaml
kubectl get events --field-selector source=cluster-autoscalerCA eventsreason=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 ""
Note: 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)

Confirm the CA setting for userpool:
az aks nodepool show -g $RG --cluster-name $CLUSTER -n userpool --query "{auto:enableAutoScaling,min:minCount,max:maxCount,count:count}" -o table
Create Pending pods: scale myapp to 30 replicas (250m each, so 7.5 cores of requests, which exceeds the remaining capacity of the 3 userpool nodes):
kubectl -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)}]
Watch the new nodes join (usually 2–4 minutes):
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.

Reduce the load and watch scale-down: first tune the profile to react faster so you can observe it in class:
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
Create a node that cannot scale down: add an annotation that blocks scale-down to one node, repeat the previous step, and watch that node stay:
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-
Cleanup: restore the default profile: 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.

Command-line exercises
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
Scenario analysis
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

▶
AKS Automatic Scaling Deep Dive: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
AKS official channel · English · Overview of node and pod scaling in AKS
▶
Kubernetes Autoscaling: HPA vs. VPA vs. Keda vs. CA vs. Karpenter vs. Fargate — Anton Putra
English · Side-by-side comparison of scalers (examples are mainly AWS, but the mechanisms are general)

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–75s
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.
Shot 4 · 75–90s
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.
Or score ≥ 70% on the quiz

Module 3 · Node Auto Provisioning (NAP / Karpenter)

13:00 – 21:00 · No more “create a pool first, then scale it”: when a Pending pod needs something, NAP buys the most suitable VM directly
8 minGA (explicitly enabled on AKS Standard · enabled by default on AKS Automatic)karpenter.sh/v1 · karpenter.azure.com/v1beta1Windows image families in preview★★★★★
Learning goals
  • 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, and NodeClaim.
  • Write a NodePool with SKU selectors (karpenter.azure.com/sku-family, sku-cpu, karpenter.sh/capacity-type, and so on), limits, and weight. Write an AKSNodeClass with imageFamily, osDiskSizeGB, and maxPods.
  • Understand consolidation (WhenEmpty / WhenEmptyOrUnderutilized), drift, expiration, disruption budgets, and karpenter.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.
Prerequisites: Modules 1 and 2. Importance: ★★★★★

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).

ObjectAPIWho maintains itPurpose
NodePoolkarpenter.sh/v1You (NAP creates default and system-surge by default)Constraints: allowed SKUs, capacity types, zones, and architectures; taints and labels; limits, weight, and disruption policy
AKSNodeClasskarpenter.azure.com/v1beta1You (default by default)Azure-side settings: imageFamily (Ubuntu / AzureLinux / AzureContainerLinux), osDiskSizeGB (default 128, minimum 30), maxPods, vnetSubnetID, kubelet, GPU, and tags
NodeClaimkarpenter.sh/v1NAPA 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

  1. kube-scheduler cannot schedule the pod, so it sets PodScheduled=False / Unschedulable.
  2. Karpenter's provisioner sees the Pending pod and collects pods that arrive together within a short batching window.
  3. 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.
  4. 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: cilium label precisely so the overhead can be predicted) and on price. When both Spot and On-demand are allowed, it prefers Spot.
  5. 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 the karpenter.sh/nodepool label and a startup taint (Cilium's node.cilium.io/agent-not-ready).
  6. After the kubelet registers and the CNI is ready, the startup taint is removed, and kube-scheduler binds the pod.

Disruption mechanisms

MethodTypeConfigurationLimited by NodePool budgets?
ConsolidationAutomatic, gracefulspec.disruption.consolidationPolicy: WhenEmpty | WhenEmptyOrUnderutilized, consolidateAfter (can be set to Never)Yes
DriftAutomatic, gracefulChanging the NodePool template or AKSNodeClass (tags are the exception)Yes
ExpirationAutomatic, forcedexpireAfter (Never for the default pool)No (but PDBs are still respected when evicting pods)
ManualForcedkubectl delete node / nodeclaim / nodepoolNo

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)

ItemNAP support
Azure CNI OverlaySupported (recommended, with the Cilium dataplane)
Azure CNI Node SubnetSupported
Azure CNI Pod Subnet (dynamic IP allocation)Not supported
kubenet / Calico network policyNot supported
IPv6 single-stackNot supported (dual-stack is in preview)
  • Windows node pools are outside NAP's official support scope (the Windows2022/2025 image 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)

ScenarioRecommendation
Most new production workloadsAKS Automatic (NAP preconfigured, with an SLA for pod readiness)
Needs fine-grained platform customizationAKS Standard + NAP
Windows, kubenet, the need to stop the cluster, or a fixed VMSS operations modelAKS Standard + CA

Comparison with similar practices

AKS NAPSelf-managed Karpenter (Azure provider)EKS Karpenter
Where it runsManaged control plane, upgraded by AKSInstalled in the cluster with Helm, upgraded by youIn the cluster (managed in EKS Auto Mode)
Node classAKSNodeClassAKSNodeClassEC2NodeClass
SupportedMicrosoft supportCommunityAWS
Common misconceptions ① "NAP nodes live in a VMSS, so I can adjust them with 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

Pending Podrequests + constraints + tolerations Karpenter (NAP, managed)provisioner: batching + requirement intersectionChoose SKU (price, Spot preferred)disruption: consolidation / drift NodePoolkarpenter.sh/v1 AKSNodeClasskarpenter.azure.com/v1beta1 nodeClassRef Reads NodeClaim (created by NAP)instance-type · zone · capacity-type Azure: a separate VM + NIC + OS disk in the node resource groupFor example Standard_D8as_v5 · canadacentral-2 · SpotTemporary OS disk (used automatically when it satisfies osDiskSizeGB) Node ReadyScheduler binds the pod Delete NodePool → cascade-deletes NodeClaims → nodes are tainted and drained, then deleted (finalizers guarantee the order)
Figure 3-1: the NodePool constrains "what can be bought", AKSNodeClass decides "how it is configured on Azure", and a NodeClaim is one specific purchase

Flowchart: how CA and NAP decisions differ

Cluster Autoscaler Candidates = existing node pools (one SKU per pool) Action = increase a VMSS's capacity by +N Pod needs 24Gi, the largest pool has 13.5Gi → cannot scale up Scale-down = delete low-utilization nodes (no swapping for smaller ones) Tuning = cluster-wide profile Strengths: mature, predictable, supports Windows / stop NAP (Karpenter) Candidates = all SKUs allowed by the NodePool Action = create a NodeClaim (one suitable VM) Pod needs 24Gi → choose E4as_v5 / D8as_v5, etc. Scale-down = delete, or replace with a cheaper node Tuning = per-NodePool disruption/budgets Limitations: network requirements, cannot stop, Windows preview
Figure 3-2: the same Pending pod. CA can only pick from an existing menu, while NAP can make one to order based on need.

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.

Cluster Autoscaler
    NAP (Karpenter)

      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

      CommandPurposeKey parameters
      az aks create --node-provisioning-mode AutoCreate a new cluster with NAP enabled--network-plugin azure --network-plugin-mode overlay --network-dataplane cilium
      az aks update --node-provisioning-mode AutoEnable on an existing cluster--node-provisioning-default-pools Auto|None
      az aks update --node-provisioning-mode ManualDisable (drain NAP nodes first)See the steps below
      kubectl get nodepools,aksnodeclasses,nodeclaimsView NAP objects-o wide, describe
      kubectl get events --field-selector source=karpenter-eventsNAP eventsControl plane log category node-auto-provisioning
      kubectl get nodes -l karpenter.sh/nodepoolList 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)

      Cost / permissions / risk New cluster (Standard tier control plane + 2×D4s_v5 ≈ US$0.4/hour) + nodes created on demand by NAP (example estimate US$0.1–1/hour). Requires Contributor on the resource group. NAP clusters cannot be stopped, so be sure to delete the cluster when the lab is finished.
      Create the cluster and apply nap-batch.yaml (see the "Commands" tab).
      Submit a Job that needs the batch pool:
      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.

      Check the node labels and events:
      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
      Watch consolidation: after the Job completes (about 5 minutes), the node becomes empty and is deleted after 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
      Watch drift: change 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'
      Cleanup: 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.

      Command-line exercises
      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
      Scenario analysis
      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

      ▶
      AKS Node Auto Provisioning (NAP) - Feature Overview (Azure Kubernetes Service) — Azure Kubernetes Service (AKS)
      AKS official channel · English · NAP feature overview
      ▶
      Node Auto Provisioning with Wilson Darko: (NAP) AKS Troubleshooting Series — Azure Kubernetes Service (AKS)
      AKS official channel · English · NAP troubleshooting (Wilson Darko is also an author of the NAP documentation)
      ▶
      Karpenter for Azure - Hands on with AKS Node Auto Provisioning — Programming with Wolfgang
      English · Hands-on demo (community channel; NAP may still have been in preview when recorded, so follow the commands in this hour)

      Official documentation

      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.

      Shot 1 · 0–20s
      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.
      Shot 2 · 20–45s
      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.
      Shot 3 · 45–75s
      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.
      Shot 4 · 75–100s
      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.
      Or score ≥ 70% on the quiz

      Module 4 · Pod scaling: HPA, the KEDA add-on, and VPA

      21:00 – 28:00 · The pod layer decides "how many and how big", and the node layer (CA/NAP) makes sure they fit. Design both layers together.
      7 minHPA autoscaling/v2 GAKEDA add-on GA (1.36: 2.19 · 1.37: 2.20)VPA add-on (InPlaceOrRecreate on 1.34+)★★★★☆
      Learning goals
      • Calculate the HPA's desired replicas (ceil(current replicas × current metric / target)), and use behavior to control the scaling speed and stabilization windows.
      • Install the KEDA add-on with --enable-keda, write a ScaledObject (Redis list, cron, Azure Service Bus) and a TriggerAuthentication (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 among Off / Initial / Recreate / InPlaceOrRecreate, and avoid conflicts with HPA on the same metric.
      Prerequisites: the HPA/VPA principles from hour 6 of the K8s course; Modules 2 and 3. Importance: ★★★★☆

      What: three types of pod scalers

      HPAKEDA (AKS add-on)VPA (AKS add-on)
      What it changesReplica countReplica count (including scale-to-zero)Container requests (and limits, proportionally)
      Based onResource metrics (metrics-server), custom/external metrics70+ event source scalers: queue length, cron, Prometheus, Kafka lag, and moreHistorical CPU/memory usage and OOM events
      AKS installationBuilt in (metrics-server is managed by AKS)az aks update --enable-kedaaz aks update --enable-vpa
      VersionFollows K8sPinned minor version per K8s release: 1.35 → 2.17, 1.36 → 2.19, 1.37 → 2.201.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.policies can 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 implements external.metrics.k8s.io), and keda-admission-webhooks in kube-system, with 2 replicas each.
      • You create a ScaledObject (keda.sh/v1alpha1), and KEDA generates an HPA named keda-hpa-<name> for it. Activation and deactivation between 0 and 1 replicas is handled by the operator, using pollingInterval (default 30 seconds) and cooldownPeriod (default 300 seconds). For batch work, use ScaledJob.
      • 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), and vpa-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). Auto has 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; RequestsOnly changes only requests.

      When: choosing and combining

      ScenarioRecommendation
      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-zeroKEDA (queue length / cron), can scale to 0
      Monoliths that are hard to scale out, JVM heap tuningVPA (Initial or InPlaceOrRecreate)
      Using HPA and VPA on the same workloadOnly 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-onSelf-installed KEDA (Helm)Azure Container Apps scaling
      UpgradeWith the AKS versionYour responsibilityBuilt into the platform (runs KEDA underneath)
      CustomizableHelm values cannot be changedFully customizableRule-level
      SupportedMicrosoft support (GA K8s versions)CommunityMicrosoft
      Common misconceptions ① "KEDA replaces HPA": KEDA generates and drives an HPA, so do not create a separate HPA manually for the same Deployment. ② "VPA Auto adjusts in place": Auto is equivalent to Recreate (eviction). For in-place adjustment, use 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

      Event sourceRedis list / Service Bus kube-system (add-on)keda-operator: polls scalers, 0↔1keda-operator-metrics-apiserverexternal.metrics.k8s.io ScaledObjectkeda.sh/v1alpha1 HPA keda-hpa-*1↔N (every 15s) Deploymentreplicas 0…20 Pending pods → CA / NAP add nodesModules 2 / 3 VPA (the other path): recommender → updater → admission-controllerChanges requests: Off / Initial / Recreate / InPlaceOrRecreate
      Figure 4-1: KEDA handles "activation + external metrics", but the HPA still changes the replica count; node scaling takes over when pods don't fit

      Flowchart: end-to-end timeline of a traffic burst

      t=0 traffic rises ~30–60s metrics visible HPA sync → replicas +N Some pods Pending CA triggers within 10s / NAP batching ~2–4 min nodes Ready Pod Ready
      Figure 4-2: node boot is the longest segment (illustrative values). Shorten it with headroom, warm-up (cron), or faster image pulls (Artifact Streaming).

      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

      CommandPurposeDescription
      kubectl autoscale deploy myapp --cpu-percent=60 --min=3 --max=20Quickly create an HPAProduction YAML (autoscaling/v2 + behavior)
      az aks update --enable-keda / --disable-kedaKEDA add-onVerify: --query workloadAutoScalerProfile.keda.enabled
      az aks update --enable-vpa / --disable-vpaVPA add-onCLI ≥ 2.52.0
      kubectl get hpa,scaledobject -n myappView scaling objectsREADY/ACTIVE columns of the ScaledObject
      kubectl describe vpa NAMEView recommendationsLower 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)

      Cost The KEDA/VPA add-ons are free themselves and use only a small amount of node resources. Scaling out may add nodes to userpool (see the Module 2 estimate).
      HPA + load test:
      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.

      Enable KEDA and deploy the worker (the worker simulates consumption with redis-cli BRPOP, 2 seconds per message):
      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
      Enqueue 60 messages and watch 0 → 12 → 0:
      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.

      Enable VPA and read myapp's recommendations (Off mode, does not change the pods):
      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"}}
      Cleanup: 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.

      Command-line exercises
      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"}'
      Scenario analysis
      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

      ▶
      KEDA: Kubernetes Event-Driven Autoscaling — DevOps & AI Toolkit
      English · KEDA principles and demo (Viktor Farcic's channel)
      ▶
      Scaling Explained Through Kubernetes HPA, VPA, KEDA & Cluster Autoscaler — DevOps & AI Toolkit
      English · How the four scalers relate
      ▶
      Understanding CPU & Memory with the Kubernetes Vertical Pod Autoscaler — That DevOps Guy
      English · What VPA recommendations mean (recorded earlier; follow this hour for InPlaceOrRecreate)

      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.

      Shot 1 · 0–20s
      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.
      Shot 2 · 20–50s
      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.
      Shot 3 · 50–75s
      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.
      Shot 4 · 75–90s
      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.
      Or score ≥ 70% on the quiz

      Module 5 · Spot node pools and cost optimization

      28:00 – 35:00 · Use Azure's spare capacity for a large discount, at the cost of "it can be reclaimed at any time". Only use it for workloads that can be interrupted.
      7 minSpot node pools GANo SLA★★★★☆
      Learning goals
      • 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: spot and the taint kubernetes.azure.com/scalesetpriority=spot:NoSchedule that 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.
      Prerequisites: Modules 1–3. Importance: ★★★★☆

      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, and spot-max-price cannot be changed after creation. The max price must be -1 or a positive number with at most 5 decimal places (USD per hour).
      • AKS automatically adds the label kubernetes.azure.com/scalesetpriority:spot and the taint kubernetes.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 Deallocate eviction policy, stopped instances still count against compute quota, which can cause scale-up or upgrade failures. Usually choose Delete (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

      1. Azure sends a Preempt event through Scheduled Events (Spot VMs usually get up to about 30 seconds of notice), and then deletes (or deallocates) the VM.
      2. The node becomes NotReady or disappears, the pods on it lose their runtime, and their controllers recreate them elsewhere, so they may go Pending.
      3. 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"

      ApproachHow to implementNotes
      A. Pods prefer SpotPods tolerate the Spot taint + a preferredDuringScheduling affinity for Spot nodes; they can also schedule onto regular poolsWhen CA scales up, the expander decides which pool is used, which is not necessarily the Spot pool
      B. CA priority expanderexpander=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. NAPNodePool karpenter.sh/capacity-type: [spot, on-demand]: when both are allowed, NAP prefers Spot and chooses on-demand if Spot is unavailableSimplest; 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

      LeverEffectWhere it appears in this course
      Right-size requests (VPA recommendations)Reduces capacity that is reserved but unusedModule 4
      CA with a sensible profile / NAP consolidationReclaims idle nodes promptly and switches to smaller sizesModules 2 and 3
      KEDA scale-to-0 + user pool min 0Zero cost at night / when idleModule 4
      Spot pool / NAP spotLarge discount for batch workThis module
      Reserved instances / Azure savings plansDiscount on stable baseline capacity (billing-level, unrelated to cluster configuration)—
      Dev clusters: az aks stop; pool scaleDownMode: DeallocateOnly disk costs while stoppedModule 0
      Cost analysis add-on (az aks update --enable-cost-analysis, requires Standard/Premium tier)Allocates cost by namespace/workloadHour 6

      Comparison with similar practices

      AKS Spot poolsAWS Spot (EKS)GCP Spot VMs (GKE)
      Eviction noticeScheduled Events (about 30 seconds)2-minute interruption noticeAbout 30 seconds
      Automatic taintYes (scalesetpriority=spot)No (configure yourself)Optional
      Price capMax price or -1 can be setCan be setNone
      Common misconceptions ① "Spot pools automatically fall back to regular pools": they don't. You need to design approach A, B, or C yourself. ② "A PDB protects against Spot evictions": evictions are forced by the infrastructure and do not go through the Eviction API, so PDBs don't apply. Upgrading a Spot pool also does not drain. ③ "A lower max price saves more money": if the price exceeds the cap, the node is evicted. -1 means evicted only for capacity reasons, and billing uses the current Spot price (no higher than on-demand). ④ "Deallocate is better because you can recover after an eviction": stopped instances keep using quota.

      Architecture diagram: division of work between Spot and regular pools

      Workload myapp (online)No Spot toleration report Job (interruptible)tolerates spot + affinitycheckpoint / retryable userpool (Regular)D4s_v5 · CA 3–9 · zones 1 2 3On-demand price · SLA spotpool (Spot)D8as_v5 · CA 0–20 · Delete · max -1taint scalesetpriority=spot:NoSchedule Fallback when Spot is insufficient (approaches A/B/C) Azure reclaims capacityScheduled Events: PreemptVM deleted after ≈30s
      Figure 5-1: online services go on regular pools, and interruptible tasks go on Spot pools; the fallback path must be designed explicitly

      Flowchart: recovery process after a Spot eviction

      Preempt eventVM deleted Node disappearsPod recreated → Pending CA scales up the Spot poolor restores min-count Spot capacity insufficient?backoff Fallback: regular poolJob resumes from checkpoint
      Figure 5-2: a PDB cannot block Spot evictions; reliability comes from replica redundancy, retries, and checkpoints

      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.

      Spot node
      Regular / on-demand node

      Core commands and parameters

      ParameterValuesDescription
      --priorityRegular (default) / SpotCannot be changed after creation
      --eviction-policyDelete (default) / DeallocateDeallocate 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)

      Cost / risk 1–3 D8as_v5 Spot VMs (sample estimate, a small fraction of the on-demand price). If Spot capacity is insufficient, node pool creation can fail (SkuNotAvailable / allocation failure). You can switch to D4as_v5 or D8s_v5. A simulated eviction deletes the Pods running on that VM.
      Create the Spot pool (see the Commands tab).
      Run the Indexed Job:
      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).

      Simulate a Spot eviction (run simulate-eviction on a VMSS instance):
      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).

      Check the Job result: kubectl -n myapp get job report -o jsonpath='{.status.succeeded}/{.spec.completions} failedIndexes={.status.failedIndexes}{"\n"}'
      Clean up: 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.

      Command-line exercises
      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)"; done
      Scenario analysis
      Your 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

      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.

      Shot 1 · 0–20s
      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.
      Shot 2 · 20–45s
      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.
      Shot 3 · 45–65s
      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.
      Shot 4 · 65–80s
      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.
      Or score ≥ 70% on the quiz

      Module 6 · GPU and specialized workloads

      35:00 – 42:00 · GPU nodes are expensive, scarce, and slow to start. Use a dedicated pool, taint isolation, and scale to 0, and let AKS manage the drivers and device plugin.
      7 minAKS managed GPU (--enable-managed-gpu, CLI ≥ 2.85)--skip-gpu-driver-install retired on 2025-08-14★★★☆☆
      Learning goals
      • 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 the sku=gpu:NoSchedule taint, and have Pods request resources with nvidia.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.
      Prerequisites: Modules 1–3; Kubernetes extended resources (device plugin). Importance: ★★★☆☆ (★★★★★ if you are building an AI platform)

      What: the components that run GPUs on AKS

      ComponentPurposeFully managedDriver only (default)BYO
      NVIDIA GPU driverKernel module and user-space librariesAKSAKSYou (for example, the GPU Operator)
      NVIDIA device pluginAdvertises nvidia.com/gpu to the kubelet (nvidia.com/mig-* when MIG is used)AKSYouYou
      DCGM + DCGM exporterGPU utilization, temperature, and other Prometheus metrics (port 19400)AKS (node label kubernetes.azure.com/dcgm-exporter=enabled)YouYou
      GPU health signalsNPD node conditions UnhealthyNvidiaDevicePlugin and UnhealthyNvidiaDCGMServicesAKS——
      CLI--enable-managed-gpu=trueNo 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

      1. The Pod declares resources.limits: nvidia.com/gpu: 1 and a toleration for sku=gpu.
      2. Scheduler filter: only nodes that advertise an allocatable nvidia.com/gpu pass. If there are no GPU nodes, the Pod stays Pending.
      3. 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.
      4. 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.
      5. The scheduler binds the Pod. The kubelet calls the device plugin's Allocate method, 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: Driver and nvidia.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 GPUNVIDIA GPU OperatorKAITO (AI toolchain add-on)
      ScopeDriver + device plugin + DCGMFull stack: driver, toolkit, plugin, DCGM, and MIG managerAutomatically provisions GPU nodes per model and deploys inference
      OperationsAKS handles itYou handle itAKS add-on (not covered in this hour)
      Common misconceptions (1) 'A GPU pool can use 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

      GPU node aks-gpupool-* (NC4as_T4_v3 · taint sku=gpu:NoSchedule) Training / inference Podlimits nvidia.com/gpu: 1 NVIDIA device pluginListAndWatch / Allocate (gRPC) kubelet + containerdnvidia-container-toolkit injects the device DCGM + dcgm-exporter :19400DCGM_FI_DEV_GPU_UTIL and others NVIDIA driver (kernel module) · Ubuntu 24.04 / Azure Linux 3.0NPD: UnhealthyNvidiaDevicePlugin / UnhealthyNvidiaDCGMServices Fully managed--enable-managed-gpu=trueAKS manages all the components above Driver only (default)Only the yellow layer; you install the plugin yourself BYO: --gpu-driver NoneEverything self-managed (GPU Operator)
      Figure 6-1: the installation setup determines how far AKS's responsibility extends

      Flowchart: cold start when the GPU pool scales to 0

      GPU Pod PendingNo nvidia.com/gpu CA / NAP scale-out0 → 1 VM startup + driverSeveral minutes Plugin advertises GPUallocatable gpu: 1 Pull large image → RunningCUDA image can reach several GB
      Figure 6-2: scaling to 0 saves money, but the cold start is long. Online inference usually keeps a minimum number of replicas or uses scheduled warm-up.

      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

      ParameterDescription
      --node-vm-size Standard_NC4as_T4_v3Minimum recommended AKS GPU pool size (1×T4)
      --enable-managed-gpu=true|falseFully managed stack / driver only (CLI ≥ 2.85.0)
      --gpu-driver NoneDo not install the driver (use with --enable-managed-gpu=false; CLI ≥ 2.72.2)
      --gpu-instance-profile MIG1g --gpu-mig-strategy Single|MixedMIG (A100/H100)
      --node-taints sku=gpu:NoScheduleIsolation (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)

      Cost / quota / risk NC4as_T4_v3 is a GPU VM size, and its price is much higher than a general-purpose VM (sample estimate of about 0.5–0.6 USD per hour; check the pricing page for current rates). New subscriptions usually have a quota of 0 for the NCASv3_T4 series, so request quota first. Delete the GPU pool as soon as the lab is done. If you have no quota, only read the Commands tab and watch the animation.
      Check quota: 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).
      Create the managed GPU pool (see the Commands tab). Takes about 6–10 minutes.
      Verify the managed components and the GPU allocatable count (see the Commands tab).
      Run nvidia-smi:
      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 |
      +-----------------------------------------+------------------------+----------------------+
      Watch it scale to 0: after you delete the Pod, CA scales the GPU pool to 0 by default after about 10 minutes: kubectl -n myapp delete pod managed-gpu-test; kubectl get nodes -l agentpool=gpupool -w.
      Clean up (required): 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.

      Command-line exercises
      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'
      Scenario analysis
      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

      ▶
      GPUs in Kubernetes for AI Workloads — DevOps & AI Toolkit
      English · general GPU scheduling in Kubernetes (not AKS-specific; for AKS parameters, follow this hour)

      No verified AKS official channel video on managed GPU node pools was found.

      Official documentation

      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.

      Shot 1 · 0–20s
      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.
      Shot 2 · 20–45s
      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.
      Shot 3 · 45–65s
      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.
      Shot 4 · 65–80s
      Visual: the terminal prints nvidia-smi output showing a Tesla T4.
      Narration: finally, nvidia-smi confirms that the container really has the GPU.
      Or score ≥ 70% on the quiz

      Module 7 · Availability: PDBs, topology spread, and zone redundancy

      42:00 – 50:00 · The autoscaler actively moves Pods around. The PDB sets how many can move at once, topology spread sets where they go, and availability zones set how much one failure can take down.
      8 minPDB policy/v1 GAtopologySpread GAZRS disks default in 1.29+★★★★★
      Learning goals
      • 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 topologySpreadConstraints for myapp. Understand maxSkew, whenUnsatisfiable, minDomains, and matchLabelKeys.
      • Design zone redundancy with zone-spanning node pools, ZRS disks, and Standard LB. Run a 'zone failure' drill (cordon and drain one zone).
      Prerequisites: PDBs and topology spread from Kubernetes hour 2; Modules 1–3. Importance: ★★★★★

      What: three lines of defense

      MechanismWhat it protectsKey fields
      PodDisruptionBudgetNumber of replicas that can be unavailable at the same time during voluntary disruptionsminAvailable or maxUnavailable; unhealthyPodEvictionPolicy: AlwaysAllow
      topologySpreadConstraintsDistribution of replicas across zones and nodestopologyKey, maxSkew, whenUnsatisfiable, minDomains, matchLabelKeys
      Zone redundancy (infrastructure)Failure of a single datacenterNode 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's status.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's terminationGracePeriod expires, it bypasses the PDB. AKS upgrades have drainTimeoutInMinutes and undrainableNodeBehavior (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 as 0 for regional pools).
      • Use whenUnsatisfiable: DoNotSchedule (hard constraint) across zones and ScheduleAnyway (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 default Ignore, a cordoned node (with the node.kubernetes.io/unschedulable taint) 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-csi uses 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

      PDBDeployment maxUnavailablepodAntiAffinity
      When it appliesExternal evictionOwn rolling updateAt scheduling time
      GranularityAvailable count for a group of PodsSpeed of replacing old with new ReplicaSetsWho not to co-locate with
      Common pitfallsSetting it to 0 blocks scale-down and upgradesUnrelated to PDBsWhen required, the replica count is limited by the number of domains
      Common misconceptions (1) 'PDBs can prevent Spot eviction or zone failures.' They cannot. (2) '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

      Standard LB (zone-redundant) canadacentral-1 canadacentral-2 canadacentral-3 userpool node amyapp ×1 userpool node bmyapp ×1 userpool node cmyapp ×2 userpool node dmyapp ×1 userpool node emyapp ×1 ZRS disk (managed-csi)Can be re-attached in any zone PDB maxUnavailable: 1zone skew ≤ 1 (DoNotSchedule) node skew ≤ 1 (ScheduleAnyway)6 replicas: 2 / 2 / 2
      Figure 7-1: 2 replicas per zone. If any one zone fails, 4 replicas remain. The PDB controls how fast voluntary disruptions can proceed.

      Flowchart: how the PDB decides on an eviction request

      drain / CA / NAP / upgradePOST …/pods/x/eviction API server checks the PDBdisruptionsAllowed > 0 ? 201: Pod deleteddisruptionsAllowed - 1 429 Too Many RequestsThe eviction caller waits and retries Timeout policyCA 600s / NAP TGP / upgrade drainTimeout
      Figure 7-2: PDBs only apply to the Eviction API. Each eviction caller has its own timeout and give-up policy.

      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

      CommandPurposeDescription
      kubectl get pdb -ACheck ALLOWED DISRUPTIONSA PDB with 0 blocks scale-down and upgrades
      kubectl drain NODE --ignore-daemonsets --delete-emptydir-dataManual drain--timeout, --disable-eviction (bypasses the PDB; use with caution)
      kubectl get pod -o wide -L topology.kubernetes.io/zoneWhich node a Pod is onZone labels are on the nodes; see the script below
      kubectl get nodes -L topology.kubernetes.io/zoneZone of the nodeRegional 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)

      Apply the PDB and topology spread (see the Commands tab), and confirm the 2/2/2 distribution.
      Start a client that sends continuous requests (count the non-200 responses):
      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
      Simulate a zone failure drill: drain zone 1 (through the Eviction API):
      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.

      Recovery: 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.
      Clean up: 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).
      Risk: only drain an entire zone in a lab cluster. In production, run zone drills during a maintenance window, or use Azure Chaos Studio's AKS faults (follow the official docs).

      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.

      Command-line exercises
      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 -c
      Scenario analysis
      myapp 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

      ▶
      Pod Topology Spread Constraints in Kubernetes — Lukonde Mwila
      English · topology spread constraints explained (general Kubernetes)
      ▶
      Kubernetes Pod Disruption Budgets | How to keep your workloads online during planned maintenance — Drewbernetes
      English · PDBs and planned maintenance

      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.

      Shot 1 · 0–20s
      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.
      Shot 2 · 20–45s
      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.
      Shot 3 · 45–70s
      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.
      Shot 4 · 70–90s
      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.
      Or score ≥ 70% on the quiz

      Module 8 · Scaling review and common errors

      50:00 – 60:00 · Turn the first seven modules into a checklist for review before go-live, and use a troubleshooting tree to handle 'can't scale out', 'won't scale in', and flapping back and forth.
      10 minComprehensive★★★★★
      Learning goals
      • 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.
      Prerequisites: Modules 1–7. Importance: ★★★★★

      What: scaling review checklist

      DimensionCheck itemHow to check
      Capacity baselineAll containers have requests; requests are within 2× of actual usage; the system pool is separate and spans at least 3 nodes across zonesVPA Off recommendations, kubectl top, az aks nodepool list
      Pod scalingOnline 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 reasonablekubectl get hpa,scaledobject,vpa -A
      Node scalingUser 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 handaz aks show --query autoScalerProfile, kubectl get nodepools
      CostInterruptible workloads run on Spot; idle pools can scale to 0; GPU pools have min 0 or a clear reason not to; consolidation is enabledCost analysis add-on, node utilization
      Availability≥ 3 replicas, PDB maxUnavailable 1 + AlwaysAllow, cross-zone topology spread, ZRS storage; no PDB with ALLOWED=0kubectl get pdb -A
      ObservabilityEnable control plane logs for cluster-autoscaler and node-auto-provisioning; alert on Pending Pods lasting over 10 minutes, unhealthy CA, and NodeClaim startup failuresDiagnostic 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

      #ErrorSymptomFix
      1No requests, or requests far too smallNode CPU is maxed out but does not scale out; HPA shows <unknown>Set requests (use VPA recommendations)
      2Requests far too largeNode utilization is low but Pods are Pending, and cost is highRaise requests
      3max-count / NodePool limits too smallmax node group size reachedRaise them, and check quota and IPs
      4vCPU quota or subnet IPs insufficientScale-out fails, node creation errorsRequest quota; use Overlay; expand the subnet
      5PDB allows no disruptionNo scale-down, upgrade stuckmaxUnavailable 1 + AlwaysAllow
      6A single large Pod exceeds the allocatable capacity of a single node in every poolCA NotTriggerScaleUpLarger-SKU pool or NAP
      7HPA and VPA both control CPUReplicas and requests oscillateVPA Off, or VPA manages memory only
      8Manually changing VMSS capacity or autoscaling in the MC_ resource groupNode count conflicts with CA, and state becomes inconsistentOnly use az aks / CA
      9Online services entirely on Spot, or Spot without a fallbackService interrupted when Spot is reclaimedRegular-pool baseline + fallback design
      10Scale-down too aggressive, or NAP budgets too looseFrequent node and Pod moves, many cold startsRaise 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-autoscaler scrape target, which is off by default, to get cluster_autoscaler_unschedulable_pods_count, cluster_autoscaler_unneeded_nodes_count, cluster_autoscaler_cluster_safe_to_autoscale, and cluster_autoscaler_scale_down_in_cooldown (details in Prometheus hour 3).
      • Logs: in diagnostic settings, enable the cluster-autoscaler and node-auto-provisioning categories. 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 checklistAzure Well-Architected (AKS)AKS Deployment Safeguards
      FormatManual review + scriptsArchitecture guidance and assessmentEnforced by Azure Policy (for example, requiring requests, or validating PDBs)
      TimingBefore go-live and periodicallyDesign phaseAt every deployment
      Common misconceptions (1) 'Enabling CA means you have elasticity.' Without HPA or KEDA the replica count never changes, so CA has nothing to do. (2) 'Looking at node CPU is enough to diagnose scaling.' Check Pending Pods, the requests allocation rate, and the CA and NAP events. (3) 'One review is enough.' Kubernetes version upgrades change add-ons and defaults (for example, Ubuntu 24.04 becomes the default OS in 1.35+, and VPA Auto mode is deprecated).

      Architecture diagram: the four-layer chain of scaling

      (1) Resource declarationrequests / limitsVPA recommendationsErrors 1, 2, 7 (2) Pod scalingHPA / KEDAmin/max, behaviorError 7 (3) Node scalingCA pools / NAP NodePoolQuota, IPs, SKUs, SpotErrors 3, 4, 6, 8, 9, 10 (4) Disruption protectionPDBs, topology, zonesdo-not-disruptErrors 5, 10 During a review, check from left to right. An error in an earlier layer can make a later layer look broken.
      Figure 8-1: resource declaration → Pod scaling → node scaling → disruption protection. The 10 error types are spread across the four layers.

      Flowchart: diagnostic order when a Pod has been Pending for more than 5 minutes

      FailedSchedulingdescribe pod CA / NAP eventsTriggered? NotTriggered? Status objectsstatus CM / nodeclaims Azure sideQuota / SKU / subnet Fix + alertsAdd to the review checklist
      Figure 8-2: first check what the scheduler says, then why the autoscaler did or did not act, and finally whether Azure can provide the resources.

      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)

      Save and run the review script (see the Commands tab): chmod +x scaling-review.sh && RG=$RG CLUSTER=$CLUSTER ./scaling-review.sh | tee review-$(date +%F).txt
      In the scorer on the Animation tab, check your actual situation, and record the score.
      Write one remediation item for each check that fails (owner, deadline, related module). For example: 'legacy/billing-api PDB minAvailable=100% → maxUnavailable 1 (Module 7)'.
      Set up an alert (optional): in Log Analytics, use the KQL KubePodInventory | where PodStatus == "Pending" | summarize count() by bin(TimeGenerated, 5m) (Container Insights) to create a log alert for 'Pending Pods lasting 10 minutes'.
      Practice with the troubleshooting tree: on the Troubleshooting tab, walk through the path for 'myapp Pods scaled out but stuck in Pending' in the interactive tree.

      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.

      Command-line exercises
      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 jsonc
      2. 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
      Scenario analysis
      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

      ▶
      AKS Automatic Scaling Deep Dive: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
      AKS official channel · English · good for an overall recap before the scaling review
      ▶
      Kubernetes Autoscaling: HPA vs. VPA vs. Keda vs. CA vs. Karpenter vs. Fargate — Anton Putra
      English · side-by-side comparison of scalers

      Official documentation

      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.

      Shot 1 · 0–20s
      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.
      Shot 2 · 20–45s
      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.
      Shot 3 · 45–80s
      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.
      Or score ≥ 70% on the quiz

      Command cheat sheet

      AKS scaling and node management · every code block can be copied with one click (variables: RG=rg-aks-lab; LOC=canadacentral; CLUSTER=aks-lab)
      After-class reference

      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 NODE

      Cleanup

      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 / errorMost likely causeFirst commandModule
      FailedScheduling Insufficient cpu, but no TriggeredScaleUpPool does not have CA enabled / at max / Pod too large / taintkubectl get events --field-selector reason=NotTriggerScaleUp -A2
      TriggeredScaleUp but the node never appearsQuota, zonal capacity, subnet IPs, policykubectl get cm -n kube-system cluster-autoscaler-status -o yaml2, 8
      Node is idle but not scaling downPDB=0, bare Pods, kube-system Pods, annotationskubectl get pdb -A2, 7
      NAP does not create nodesNodePool requirements do not intersect / limits exhausted / taintkubectl get events -A --field-selector source=karpenter-events3
      HPA <unknown>No CPU requestskubectl describe hpa4
      ScaledObject READY Falsescaler connection/authenticationkubectl -n kube-system logs deploy/keda-operator4
      Spot pool stays at 0 nodesCA not enabled / no Spot capacityaz aks nodepool show -n spotpool5
      Insufficient nvidia.com/gpuNo device plugin (driver-only mode)kubectl get node -o jsonpath='{.status.allocatable}'6
      Drain stuck: violates disruption budgetPDB too strictkubectl get pdb -A7

      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

      Build a scaling setup for myapp that is elastic, cost-efficient and resilient to zone failures, then verify it with a load test and a zone drain
      After class ≈ 45 minutesCovers all modules
      Scenariomyapp is about to run a promotion. Requirements: ① system and business workloads are isolated; the business pool spans 3 zones, uses Azure Linux, and has CA enabled; ② myapp autoscales on CPU, with pre-warming during weekday daytime; ③ the order export task (worker) scales on Redis queue length, can scale to 0, and runs on Spot; ④ when any zone is drained, myapp serves no error requests; ⑤ deliver a scaling review report and a cost estimate. Complete this in rg-aks-lab / aks-lab / the namespace myapp.
      Node pool topology (Module 1): confirm that syspool (System, CriticalAddonsOnly, 3 zones) and userpool (User, AzureLinux, 3 zones, CA 3–9, maxPods 110) exist.
      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 jsonc
      CA profile (Module 2): az 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-waste
      Spot pool (Module 5): spotpool (D8as_v5, Delete, -1, CA 0–6, label workload=batch).
      myapp scaling (Modules 4 and 7): delete the manual HPA, apply myapp-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
      Run the worker on Spot and scale it by queue (Modules 4 and 5): add a Spot toleration and a required affinity to 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.yaml
      Verify elasticity: load-test myapp (using the load Pod from Module 4) and enqueue 200 queue messages. Record the HPA replica changes, the node changes in userpool and spotpool, and the time until the first worker is Running.
      kubectl -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
      Verify availability: run the probe client, drain the userpool nodes in zone 1 (the Module 7 lab), confirm bad=0, then uncordon.
      Review and cleanup: run 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).
      Acceptance checklist

      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

      Basis for verifying all technical facts in this hour (Verified on: 2026-11-15)
      TopicVerification resultSources (accessed 2026-11-15)
      Supported versions and componentsGA: 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.1Supported Kubernetes versions (updated 2026-10-21)
      Cluster AutoscalerEnable, 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 allowedUse the cluster autoscaler in AKS (updated 2026-11-02)
      NAPBuilt 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-eventsNAP overview · Enable/disable NAP (updated 2026-11-05)
      NAP NodePool / AKSNodeClassNodePool 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 OverlayConfigure NodePools · AKSNodeClass (updated 2026-11-11)
      NAP disruption and networkingconsolidationPolicy 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 previewDisruption · 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 InPlaceOrRecreateInstall 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 RequestsAndLimitsUse the VPA in AKS
      Spot node poolsCommands 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 recommendedAdd an Azure Spot node pool
      GPUManaged 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 GPUsAKS-managed GPU nodes (updated 2026-11-11) · Use GPUs on AKS
      Node pools, quota and reservationsSystem 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%) + 100MiSystem pools · Quotas · Resource reservations
      OS SKUUbuntu: 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-skuUpgrade OS version · Use Azure Linux
      Availability zoneszone-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 previewConfigure availability zones
      PDB / topology spread / HPAUpstream Kubernetes semanticsPDB · 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 consolidateAfter can 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 puts expireAfter under spec.disruption; this hour follows karpenter.sh/v1 and the default pool and puts it under spec.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/gpu in NodePool limits is a general Karpenter capability, and no example was found in the AKS docs.
      • The raw format of the cluster-autoscaler-status ConfigMap 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.