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:

DimensionContainer Scaling (Deployment / Pod)Host Scaling (MachineDeployment / Machine)
Execution DomainShared Linux kernel namespaces and cgroupsHypervisors, physical bare metal, cloud API planes
Provisioning LatencyMilliseconds to secondsMinutes (VM boot, disk attach, OS initialization)
Bootstrap ComplexityContainer image pull and entrypoint executionOS cloud-init, security hardening, CNI IPAM, kubelet TLS bootstrap
Scale-Down ImpactLocal process termination (SIGTERM / SIGKILL)Node cordoning, Pod eviction, CSI detach, hypervisor destruction
Failure ConsequencesPod restart or rescheduling to another nodeOrphaned cloud VMs, leaked EBS/persistent disks, split-brain nodes
Safeguard EnforcementterminationGracePeriodSecondsPodDisruptionBudgets, 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:

  1. You mutate MachineDeployment.spec.replicas.
  2. The MachineDeployment controller propagates the new target replica count to the active MachineSet.
  3. The MachineSet controller compares desired replicas against existing Machine objects.
  4. For any difference, the MachineSet creates new Machine resources (on scale-up) or selects existing Machine resources for deletion (on scale-down).
  5. The Machine controller 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

  1. Drift Detection: The MachineSet controller notices spec.replicas (5) > status.replicas (3). It computes that 2 new machines are required.
  2. Template Cloning: For each new machine, MachineSet creates:
    • A Machine CR referencing the cluster and parent MachineSet.
    • A concrete bootstrap config (e.g., KubeadmConfig) cloned from spec.template.spec.bootstrap.configRef.
    • A concrete infrastructure machine (e.g., AWSMachine, AzureMachine) cloned from spec.template.spec.infrastructureRef.
  3. Bootstrap Secret Generation: The bootstrap provider renders cloud-init user data containing cluster CA certificates, discovery tokens, and kubeadm join flags, storing it as a Secret in the management cluster.
  4. 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.
  5. Node Registration & Identity Bridge: The operating system boots, cloud-init executes, and kubelet connects to the workload cluster API server. When kubelet registers the Node, the cloud provider integration sets Node.spec.providerID.
  6. Condition Propagation: The Machine controller matches spec.providerID between the management Machine and the workload Node, populating Machine.status.nodeRef. Once the node condition Ready = True is reported, MachineSet increments status.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:

  1. 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.
  2. 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.
  3. Unhealthy Machines: Machines with failing conditions (NodeReady = False or failing MachineHealthCheck) are terminated before healthy machines.
  4. 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:

  1. Cordoning: The Machine controller marks the workload node as unschedulable (Node.spec.unschedulable = true), preventing new pods from landing on the host.
  2. 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.
  3. 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.
  4. 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.
  5. Configurable Timeouts: To prevent scale-down from hanging indefinitely on misconfigured pods, MachineDeployment exposes 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:

CharacteristicScaling OperationRolling Update (Rollout)
Spec TriggerChange spec.replicas onlyChange spec.template (image, k8s version, instance type)
MachineSets InvolvedSingle active MachineSetTwo MachineSets (current revision and new revision)
Template HashUnchanged (machine-template-hash label is identical)New hash derived from updated template spec
Capacity ChurnOnly target delta is created or destroyedEvery machine in the fleet is progressively replaced
Safety ParametersEvaluates node drain and eviction timeoutsGoverned by maxSurge and maxUnavailable
Disruption RiskMinimal (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:

  1. Define Per-Zone MachineDeployments: Create dedicated MachineDeployment objects 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.
  2. 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, adjusting spec.replicas on the target MachineDeployment.
  • 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: InfraMachine reports InsufficientInstanceCapacity or VcpuLimitExceeded.
    • Fix: Request cloud quota increase or switch to alternative instance types in a new template.
  • Symptom: Machine is Running, but kubectl --kubeconfig workload.kubeconfig get nodes shows 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.

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 configure spec.template.spec.nodeDrainTimeout so CAPI forcefully evicts after the deadline.
  • Symptom: Events show volume detach timeouts.
    • Fix: Inspect workload cluster VolumeAttachment resources. If the cloud CSI driver failed to communicate with the cloud storage API, resolve the CSI controller authorization issue.

9. Key Takeaways

  • Scale vs. Rollout: Scaling changes spec.replicas on the existing MachineSet. A rollout updates spec.template, creating a new MachineSet and replacing machines under RollingUpdate rules.
  • 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: MachineSet chooses scale-down victims by checking for cluster.x-k8s.io/delete-machine annotations 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 nodeDrainTimeout and nodeVolumeDetachTimeout on production MachineDeployments to 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.


References & Further Reading