Scaling worker nodes in Cluster API (CAPI) appears deceptively simple on the surface: modify a single integer (spec.replicas) on a MachineDeployment.
Under the hood, however, scaling physical or virtual infrastructure hosts is fundamentally different from scaling software containers. A container scales in milliseconds by reserving kernel cgroups and namespaces on an existing host. A cluster host scales across multiple asynchronous control loops, orchestrating cloud API calls, virtual machine hypervisors, network interfaces, storage attachments, cloud-init bootstrapping scripts, and kubelet API registrations.
Even more critical is scale-down: while terminating a Pod merely reschedules an ephemeral process, destroying a worker host permanently terminates compute capacity. Doing so safely requires multi-stage orchestration: isolating the host, evicting running workloads while respecting PodDisruptionBudgets, allowing storage volumes to cleanly detach, deprovisioning cloud infrastructure, and deleting the host registration from the workload API.
Understanding Cluster API scaling requires mastering how controllers drive this reconciliation, how failure domains are balanced, how graceful drains execute, and where the Cluster Autoscaler integrates into the management hierarchy.
1. The Scaling Problem: Containers vs. Infrastructure Hosts
In Kubernetes workload management, scaling a Deployment from 3 to 10 replicas creates 7 new Pod records. The kube-scheduler assigns these pods to existing nodes that already run a container runtime, a Container Network Interface (CNI), and local storage drivers. Pod readiness is achieved within seconds.
Scaling an infrastructure host introduces operational latency, cloud API constraints, and stateful failure modes that container schedulers do not encounter:
| Dimension | Container Scaling (Deployment / Pod) | Host Scaling (MachineDeployment / Machine) |
|---|---|---|
| Execution Domain | Shared Linux kernel namespaces and cgroups | Hypervisors, physical bare metal, cloud API planes |
| Provisioning Latency | Milliseconds to seconds | Minutes (VM boot, disk attach, OS initialization) |
| Bootstrap Complexity | Container image pull and entrypoint execution | OS cloud-init, security hardening, CNI IPAM, kubelet TLS bootstrap |
| Scale-Down Impact | Local process termination (SIGTERM / SIGKILL) | Node cordoning, Pod eviction, CSI detach, hypervisor destruction |
| Failure Consequences | Pod restart or rescheduling to another node | Orphaned cloud VMs, leaked EBS/persistent disks, split-brain nodes |
| Safeguard Enforcement | terminationGracePeriodSeconds | PodDisruptionBudgets, nodeDrainTimeout, volume detachment |
Because machine provisioning is asynchronous and relatively slow, Cluster API separates fleet scaling from host lifecycle mechanics, relying on declarative controllers to reconcile drift over time.
2. The Scaling Mental Model
Worker fleet scaling in Cluster API is governed by a declarative three-tier controller hierarchy:
flowchart TD
MD["MachineDeployment<br/>(Desired Fleet Replicas)"] -->|"Reconciles replicas"| MS["MachineSet<br/>(Maintains Target Host Count)"]
MS -->|"Reconciles (N) instances"| M["Machine<br/>(Host Lifecycle & Phase)"]
M -->|"Clones template"| BC["BootstrapConfig<br/>(Kubeadm Join Secret)"]
M -->|"Clones template"| IM["InfrastructureMachine<br/>(Cloud VM Instance)"]
IM -->|"Provisions"| VM["Compute Instance"]
VM -->|"Runs cloud-init & kubelet"| NODE["Workload Cluster Node"]
M -.->|"Matches spec.providerID"| NODE
To reason about scaling operations, anchor on the division of responsibilities established across the worker hierarchy:
MachineDeployment = rollout strategy and desired fleet replicas
MachineSet = replica count reconciliation and machine selection
Machine = point-to-point host provisioning, drain, and deletion
When you scale a worker fleet:
- You mutate
MachineDeployment.spec.replicas. - The
MachineDeploymentcontroller propagates the new target replica count to the activeMachineSet. - The
MachineSetcontroller compares desired replicas against existingMachineobjects. - For any difference, the
MachineSetcreates newMachineresources (on scale-up) or selects existingMachineresources for deletion (on scale-down). - The
Machinecontroller manages the individual cloud VM lifecycle and Node binding.
3. Scale-Up Reconciliation Flow
When a worker fleet scales up (for example, from 3 to 5 replicas), Cluster API executes a multi-stage asynchronous convergence loop:
sequenceDiagram
autonumber
actor Operator
participant MD as MachineDeployment Controller
participant MS as MachineSet Controller
participant M as Machine Controller
participant BC as Bootstrap Controller
participant IM as Infrastructure Controller
participant Node as Workload Node
Operator->>MD: Set spec.replicas = 5 (was 3)
MD->>MS: Updates MachineSet.spec.replicas = 5
MS->>MS: Detects drift (desired: 5, current: 3)
MS->>M: Creates 2 Machine objects
M->>BC: Clones KubeadmConfigTemplate
M->>IM: Clones InfrastructureMachineTemplate (e.g. AWSMachine)
BC-->>M: Generates bootstrap join Secret
IM->>IM: Calls cloud API to launch VM instances
IM-->>M: Sets spec.providerID
Node->>Node: Boots VM, runs cloud-init, registers kubelet
Node-->>M: Reports Node.spec.providerID
M->>M: Binds nodeRef, sets status.phase = Running
MS->>MD: Updates readyReplicas & availableReplicas
Key Scale-Up Stages
- Drift Detection: The
MachineSetcontroller noticesspec.replicas (5) > status.replicas (3). It computes that 2 new machines are required. - Template Cloning: For each new machine,
MachineSetcreates:- A
MachineCR referencing the cluster and parentMachineSet. - A concrete bootstrap config (e.g.,
KubeadmConfig) cloned fromspec.template.spec.bootstrap.configRef. - A concrete infrastructure machine (e.g.,
AWSMachine,AzureMachine) cloned fromspec.template.spec.infrastructureRef.
- A
- Bootstrap Secret Generation: The bootstrap provider renders cloud-init user data containing cluster CA certificates, discovery tokens, and
kubeadm joinflags, storing it as aSecretin the management cluster. - Cloud Provisioning: The infrastructure provider consumes the bootstrap secret and calls the cloud API to launch the VM instances. Once launched, it populates
InfrastructureMachine.spec.providerID. - Node Registration & Identity Bridge: The operating system boots, cloud-init executes, and
kubeletconnects to the workload cluster API server. Whenkubeletregisters theNode, the cloud provider integration setsNode.spec.providerID. - Condition Propagation: The
Machinecontroller matchesspec.providerIDbetween the managementMachineand the workloadNode, populatingMachine.status.nodeRef. Once the node conditionReady = Trueis reported,MachineSetincrementsstatus.readyReplicas.
4. Scale-Down Reconciliation & Graceful Node Drain
Decreasing spec.replicas (e.g., from 5 to 3) is where operational risk concentrates. Terminating a host while pods are handling active traffic or holding persistent storage locks can cause data corruption or downtime.
Cluster API implements a deterministic, multi-phase deletion pipeline:
flowchart TD
TRIGGER["Scale-Down Triggered<br/>(spec.replicas decremented)"] --> SELECT["1. Machine Selection<br/>(Annotation, Failure Domain, Health, Age)"]
SELECT --> CORDON["2. Cordon Workload Node<br/>(spec.unschedulable = true)"]
CORDON --> DRAIN["3. Evict Pods via Eviction API<br/>(Respects PodDisruptionBudgets)"]
DRAIN --> DETACH["4. Detach CSI Storage Volumes<br/>(Waits for volume detach confirmation)"]
DETACH --> TEARDOWN["5. Deprovision Cloud VM<br/>(InfrastructureMachine deletes host)"]
CLEANUP["6. Delete Workload Node Object<br/>(Node purged from workload cluster API)"]
TEARDOWN --> CLEANUP
CLEANUP --> DELETE["7. Remove Machine CR<br/>(Finalizers cleared, resource removed)"]
Which Machine Gets Deleted First?
When scaling down, the MachineSet controller chooses which machines to terminate using a strict priority order:
- Delete-Machine Annotation: Any machine annotated with
cluster.x-k8s.io/delete-machine="yes"is selected first. This allows operators or autoscalers to target specific hosts for retirement. - Failure-Domain Imbalance: The controller evaluates failure domains (e.g., availability zones). If Zone A has 3 machines and Zone B has 2 machines, a machine in Zone A is selected to preserve multi-zone balance.
- Unhealthy Machines: Machines with failing conditions (
NodeReady = Falseor failingMachineHealthCheck) are terminated before healthy machines. - Creation Timestamp: If all else is equal, CAPI uses the newest or oldest machine depending on internal controller heuristics to minimize disruption.
The Five Deletion Safeguards
During node teardown, Cluster API applies several safety mechanisms:
- Cordoning: The
Machinecontroller marks the workload node as unschedulable (Node.spec.unschedulable = true), preventing new pods from landing on the host. - Graceful Eviction: Instead of deleting pods directly, CAPI calls the Kubernetes Pod Eviction API. This ensures
PodDisruptionBudgets(PDBs) are evaluated. If evicting a pod would violate its PDB, the eviction fails and the controller retries. - DaemonSet and Static Pod Exclusion: DaemonSet pods and mirror pods are ignored during eviction because they are tied to host lifecycle and terminate automatically when the host dies.
- Volume Detach Tracking: The controller waits for attached Persistent Volume Claims (PVCs) to cleanly detach to avoid data corruption or lock starvation on cloud storage backends.
- Configurable Timeouts: To prevent scale-down from hanging indefinitely on misconfigured pods,
MachineDeploymentexposes timeout knobs:spec.template.spec.nodeDrainTimeout: Maximum duration to wait for pod eviction before forcibly terminating the host.spec.template.spec.nodeVolumeDetachTimeout: Maximum duration to wait for volumes to detach.spec.template.spec.nodeDeletionTimeout: Maximum duration to wait for the cloud provider to confirm VM termination.
5. Scaling vs. Rolling Updates: A Critical Distinction
A common operational confusion is conflating scaling with rolling updates. While both involve changing numbers of machines, their internal controller mechanics are completely distinct:
| Characteristic | Scaling Operation | Rolling Update (Rollout) |
|---|---|---|
| Spec Trigger | Change spec.replicas only | Change spec.template (image, k8s version, instance type) |
| MachineSets Involved | Single active MachineSet | Two MachineSets (current revision and new revision) |
| Template Hash | Unchanged (machine-template-hash label is identical) | New hash derived from updated template spec |
| Capacity Churn | Only target delta is created or destroyed | Every machine in the fleet is progressively replaced |
| Safety Parameters | Evaluates node drain and eviction timeouts | Governed by maxSurge and maxUnavailable |
| Disruption Risk | Minimal (existing healthy nodes remain untouched) | Higher (workloads migrate across the entire fleet) |
Replica change → MachineSet changes replica count directly (no new revision).
Template change → MachineDeployment creates new MachineSet, shifts replicas via RollingUpdate.
6. Failure Domains and Zone-Aware Scaling
In enterprise cloud environments, worker pools must span multiple availability zones to tolerate physical datacenter outages.
Cluster API supports failure domain distribution natively:
apiVersion: cluster.x-k8s.io/v1beta1
kind: MachineDeployment
metadata:
name: prod-worker-md
spec:
replicas: 6
selector:
matchLabels:
cluster.x-k8s.io/cluster-name: prod-cluster
template:
spec:
clusterName: prod-cluster
failureDomain: "us-east-1a"
# ...
In production architectures, teams either:
- Define Per-Zone MachineDeployments: Create dedicated
MachineDeploymentobjects for each availability zone (e.g.,prod-worker-az-a,prod-worker-az-b,prod-worker-az-c). This guarantees strict capacity reservation in each zone. - Rely on ClusterClass / Managed Topologies: Use higher-level topologies that distribute machines across available infrastructure failure domains automatically.
During scale-down within a single MachineSet that spans failure domains, the controller calculates zone distributions before picking a victim machine, ensuring that downsizing does not unintentionally empty an availability zone.
7. Where Cluster Autoscaler Fits
Manual scaling via kubectl scale is suitable for planned capacity adjustments. For dynamic, demand-driven scaling, Kubernetes uses Cluster Autoscaler.
Understanding how Cluster Autoscaler interacts with Cluster API requires recognizing the architectural boundary between workload scheduling and infrastructure provisioning:
flowchart LR
subgraph WorkloadCluster["Workload Cluster"]
PODS["Pending Pods<br/>(Insufficient CPU/Memory)"] --> CA["Cluster Autoscaler"]
UNUSED["Underutilized Nodes<br/>(Low Resource Requests)"] --> CA
end
subgraph ManagementCluster["Management Cluster"]
CA -->|"Scales spec.replicas"| MD["MachineDeployment<br/>(CAPI)"]
MD -->|"Reconciles drift"| MS["MachineSet"]
MS -->|"Provisions / Drains"| M["Machines"]
end
M -.->|"Adds / Removes Nodes"| WorkloadCluster
The Separation of Responsibilities
- Cluster Autoscaler runs in or targets the workload cluster. It monitors the Kubernetes scheduler for pods that cannot be scheduled due to resource starvation (CPU, memory, GPU, affinity constraints), or nodes whose workloads can be consolidated onto fewer hosts.
- Cluster Autoscaler does NOT launch VMs directly. Instead, when configured with the CAPI cloud provider (
--cloud-provider=clusterapi), the autoscaler writes to the management cluster API, adjustingspec.replicason the targetMachineDeployment. - Cluster API reconciles the replica count, managing VM creation, bootstrap secret generation, cloud-init provisioning, and graceful node draining.
Configuring Autoscaler Bounds on MachineDeployments
Cluster Autoscaler discovers scalable pools using annotations on MachineDeployment resources:
apiVersion: cluster.x-k8s.io/v1beta1
kind: MachineDeployment
metadata:
name: worker-pool-general
annotations:
cluster.x-k8s.io/cluster-api-autoscaler-node-group-min-size: "2"
cluster.x-k8s.io/cluster-api-autoscaler-node-group-max-size: "10"
spec:
replicas: 3
# ...
When autoscaling down, the Cluster Autoscaler evaluates which specific node has the lowest utilization, annotates that machine with cluster.x-k8s.io/delete-machine="yes", and decrements spec.replicas. CAPI’s MachineSet controller prioritizes that exact annotated host for draining and deletion.
8. Practical Inspection & Troubleshooting Decision Trees
When scaling operations stall, use structured diagnostic inspections instead of guessing where the failure occurred.
flowchart TD
START["Scaling Stalled"] --> CHECK{"Operation Direction?"}
CHECK -->|"Scale-Up"| PHASE{"Machine Phase?"}
PHASE -->|"Pending"| Q1["Check Cloud Quotas & Subnet IPs<br/>in InfraMachine status"]
PHASE -->|"Provisioning"| Q2["Inspect cloud-init bootstrap log<br/>/var/log/cloud-init-output.log"]
PHASE -->|"Running without Node"| Q3["Verify CNI plugin & control plane<br/>connectivity on port 6443"]
CHECK -->|"Scale-Down"| STUCK{"Where is Deletion Stuck?"}
STUCK -->|"Drain Failing"| D1["Check PDB violations & Pods<br/>with terminationGracePeriodSeconds"]
STUCK -->|"Volume Detach"| D2["Inspect VolumeAttachments & CSI driver status"]
STUCK -->|"Infra Pending"| D3["Inspect cloud API permissions & finalizers"]
Step-by-Step Diagnostic Commands
1. Inspect Hierarchy Drift
# Compare desired, ready, and available counts across the fleet
kubectl get machinedeployments,machinesets,machines -o wide
2. Troubleshoot Stalled Scale-Up
If new machines remain stuck in Pending or Provisioning:
# Check the Machine resource conditions
kubectl describe machine <machine-name>
# Inspect the underlying infrastructure machine object
kubectl describe awsmachine <machine-name>
# (or azuremachine, vspheremachine, etc.)
- Symptom:
InfraMachinereportsInsufficientInstanceCapacityorVcpuLimitExceeded.- Fix: Request cloud quota increase or switch to alternative instance types in a new template.
- Symptom:
MachineisRunning, butkubectl --kubeconfig workload.kubeconfig get nodesshows no node registered.- Fix: SSH into the provisioned host and inspect
/var/log/cloud-init-output.log. Look for expired join tokens, network firewall blocks on port 6443, or DNS resolution failures reaching the control-plane endpoint.
- Fix: SSH into the provisioned host and inspect
3. Troubleshoot Frozen Scale-Down
If a machine targeted for deletion is stuck in Deleting:
kubectl describe machine <deleting-machine-name>
- Symptom: Events show
DrainNodeFailed: Cannot evict pod "api-gateway-0" due to PodDisruptionBudget.- Fix: A PDB configured with
minAvailable: 100%prevents pod eviction. Temporarily relax the PDB, scale the pod’s deployment, or configurespec.template.spec.nodeDrainTimeoutso CAPI forcefully evicts after the deadline.
- Fix: A PDB configured with
- Symptom: Events show volume detach timeouts.
- Fix: Inspect workload cluster
VolumeAttachmentresources. If the cloud CSI driver failed to communicate with the cloud storage API, resolve the CSI controller authorization issue.
- Fix: Inspect workload cluster
9. Key Takeaways
- Scale vs. Rollout: Scaling changes
spec.replicason the existingMachineSet. A rollout updatesspec.template, creating a newMachineSetand replacing machines underRollingUpdaterules. - Asymmetric Operational Cost: Scale-up latency is driven by cloud VM allocation and OS booting. Scale-down latency is driven by node cordoning, pod eviction, PDB validation, and storage detachment.
- Deterministic Victim Selection:
MachineSetchooses scale-down victims by checking forcluster.x-k8s.io/delete-machineannotations first, followed by failure domain balancing and node health. - Separation of Scaling Concerns: Cluster Autoscaler decides when capacity must expand or contract based on pod scheduling needs; Cluster API executes how the host lifecycle is provisioned or drained.
- Safeguard with Timeouts: Always configure
nodeDrainTimeoutandnodeVolumeDetachTimeouton productionMachineDeploymentsto prevent misbehaving application pods from blocking cluster scale-down operations.
Next in the series
Now that we understand how worker fleets scale and drain gracefully, explore Part 9: Self-Healing with MachineHealthCheck to see how Cluster API monitors node conditions and automatically remediates unhealthy hosts.