โšก
Zero to Platform Architect2026
Phase 4: Kubernetes & Scaling
Phase 4: Kubernetes & Scalingโฑ๏ธ 12 min readโšก Staff SRE Standard
๐ŸŽฏ Foundations Test Bank →

Lesson 2: Next-Gen Autoscaling with Karpenter & Spot Fleets

๐Ÿง  The Concept (Explain Like Iโ€™m 5)

Imagine you run a massive city airport bus shuttle system:

  • The Legacy Cluster Autoscaler (CAS): Whenever 3 extra passengers arrive at terminal B, the dispatcher orders an entire new 60-passenger diesel bus from the depot. It takes 10 to 15 minutes to warm up and drive over. When it finally arrives, 3 passengers get on and 57 seats sit empty. You pay the full gas bill for all 60 seats anyway.
  • Karpenter (The AI Uber Dispatcher): Karpenter inspects the exact height, weight, and luggage of the waiting passengers. If 2 business travelers arrive, it instantly dispatches a 2-seater hybrid sedan. If an Olympic team arrives with sports equipment (a GPU workload with 80GB VRAM), it dispatches a specialized cargo van. The vehicles arrive via the highway in 35 seconds, fully packed (Optimal Bin-Packing), and cost 70% to 90% less by utilizing spare rental inventory (AWS Spot Instances).

๐Ÿข The Enterprise Context: Why Platform Teams Are Ditching Cluster Autoscaler

For nearly a decade, the Kubernetes Cluster Autoscaler (CAS) was the only option. However, at enterprise scale (5,000+ pods across hundreds of microservices), CAS introduces severe architectural bottlenecks:

flowchart TD
    subgraph CASModel ["Legacy Cluster Autoscaler (ASG-Bound)"]
        direction TB
        CASPod["Pending Pod"] --> CAS["Cluster Autoscaler"]
        CAS --> ASG1["Fixed ASG 1: m5.large On-Demand"]
        CAS --> ASG2["Fixed ASG 2: c5.2xlarge Spot"]
        CAS --> ASG3["Fixed ASG 3: g4dn.xlarge GPU"]
        ASG1 --> EC2_CAS["AWS Auto Scaling Group API<br/>(10-15 min node boot time)"]
    end

    subgraph KarpenterModel ["Modern Karpenter (Group-less Direct Fleet)"]
        direction TB
        KPod["Pending Pod"] --> KController["Karpenter Controller"]
        KController --> BinPack["Algorithmic Bin-Packing<br/>(Evaluates 600+ EC2 SKUs in ms)"]
        BinPack --> EC2Fleet["Direct EC2:CreateFleet API<br/>(30-45s fast node boot time)"]
    end

Comprehensive Technical Comparison

Architectural Dimension Legacy Cluster Autoscaler (CAS) Karpenter (v1 Stable)
Infrastructure Abstraction Bound to fixed AWS Auto Scaling Groups (ASGs) Group-less: Evaluates the entire AWS EC2 instance catalog dynamically
Scaling Latency 5 to 15 minutes (ASG polling loop + EC2 launch) 30 to 45 seconds (Direct ec2:CreateFleet API call)
Node Right-Sizing Rigid (Pods must fit into pre-configured node group sizes) Dynamic: Selects the cheapest instance type that fits the pending batch
Multi-Architecture (ARM/x86) Requires separate ASGs for Graviton and Intel Seamlessly blends arm64 and amd64 in a single NodePool
Automated Consolidation Primitive (Can only terminate idle nodes) Advanced: Computes if replacing 3 underutilized nodes with 1 cheaper node saves money
Zero-Touch Patching Requires complex AMI refresh scripts or manual recycling Built-in node expiration (expireAfter: 720h) triggers rolling node drift replacement

๐Ÿ”ฌ Under the Hood: The Karpenter Provisioning & Consolidation Loop

Karpenter does not poll the API server on a periodic timer. It uses real-time Kubernetes informers to watch the pending pod queue:

flowchart TD
    PodQueue["Pod created & unschedulable<br/>(Requests: 3.5 CPU, 7Gi RAM, arm64)"] --> KarpenterLoop["Karpenter Reconciliation Loop"]
    
    subgraph SchedulingEngine ["Karpenter Scheduling Engine"]
        Filter["1. Filter EC2 Catalog<br/>(Excludes incompatible zones, architectures, capacity types)"]
        BinPack["2. Algorithmic Bin-Packing<br/>(Groups multiple pending pods together)"]
        PriceCheck["3. Price & Spot Interruption Scoring<br/>(Queries AWS Pricing API in real-time)"]
        Filter --> BinPack --> PriceCheck
    end

    KarpenterLoop --> SchedulingEngine
    PriceCheck --> CreateFleet["Call ec2:CreateFleet<br/>(Requests diversified pool: c6g.xlarge, m6g.xlarge, c7g.xlarge)"]
    CreateFleet --> NodeBoot["EC2 instance boots with minimal AL2023 OS"]
    NodeBoot --> Ready["Kubelet registers -> Pods immediately scheduled! โœ…"]

The Consolidation Engine: Continuous FinOps Optimization

Karpenter continuously audits running nodes to eliminate waste through two distinct policies:

  1. Empty Node Deletion (WhenEmpty): When all application pods leave a node (e.g. after a batch job finishes), Karpenter terminates the empty EC2 instance after a configurable cooldown (e.g. consolidateAfter: 30s).
  2. Underutilized Node Replacement (WhenUnderutilized): If Node A ($0.15/hr) is running at 15% CPU and Node B ($0.15/hr) is running at 20% CPU, Karpenter calculates whether all pods from both nodes can fit onto a single smaller Node C ($0.08/hr). If it saves money and respects all PodDisruptionBudgets, Karpenter provisions Node C, cordons and drains Nodes A & B, and terminates them!

โšก Mastering AWS Spot Instances & Interruption Handling

AWS Spot Instances allow you to purchase unused EC2 capacity at up to a 90% discount compared to On-Demand prices. The trade-off: AWS can reclaim a Spot instance with only a 2-minute warning when On-Demand capacity is needed.

Enterprise Spot Resilience Architecture

To run production microservices safely on Spot instances without user-facing downtime, platform architects implement an EventBridge + SQS Interruption Pipeline:

sequenceDiagram
    autonumber
    participant AWS as โ˜๏ธ AWS EC2 Capacity Engine
    participant EB as โšก Amazon EventBridge
    participant SQS as ๐Ÿ“ฌ Interruption SQS Queue
    participant Karpenter as ๐Ÿš€ Karpenter Controller
    participant OldNode as ๐Ÿ–ฅ๏ธ Spot Node (c6g.xlarge)
    participant NewNode as ๐Ÿ–ฅ๏ธ Replacement Spot Node (m6g.xlarge)

    AWS->>EB: 1. EC2 Spot Instance Interruption Notice (2-min warning)
    EB->>SQS: 2. Routes event to SQS queue: karpenter-interruption-queue
    Karpenter->>SQS: 3. Long-polling detects interruption message!
    Karpenter->>AWS: 4. Preemptively requests replacement node via CreateFleet
    AWS-->>NewNode: 5. New node boots and becomes Ready (35s)
    Karpenter->>OldNode: 6. Cordon node (Mark unschedulable)
    Karpenter->>OldNode: 7. Graceful Drain (Respects PodDisruptionBudgets & SIGTERM)
    Note over OldNode: Pods gracefully move to NewNode with ZERO dropped requests!
    AWS->>OldNode: 8. AWS terminates OldNode after 2 minutes

๐Ÿ’ป Production Manifests: Karpenter v1 Configuration

1. The EC2NodeClass (AWS Provider Specification)

The EC2NodeClass defines AWS-specific infrastructure parameters: subnets, security groups, AMIs, IAM instance roles, and EBS volume configurations.

apiVersion: karpenter.k8s.aws/v1
kind: EC2NodeClass
metadata:
  name: default-infrastructure
spec:
  # Minimal, fast-booting Amazon Linux 2023 kernel
  amiFamily: AL2023
  
  # IAM Role attached to the provisioned EC2 instance profile
  role: "KarpenterNodeRole-production-eks"
  
  # Discover subnets and security groups dynamically by tags
  subnetSelectorTerms:
    - tags:
        karpenter.sh/discovery: "production-eks"
  securityGroupSelectorTerms:
    - tags:
        karpenter.sh/discovery: "production-eks"
        
  # Custom root volume configuration (Fast GP3 storage)
  blockDeviceMappings:
    - deviceName: /dev/xvda
      ebs:
        volumeSize: 50Gi
        volumeType: gp3
        iops: 3000
        throughput: 125
        encrypted: true
        deleteOnTermination: true

  # Node metadata tags for FinOps billing allocation
  tags:
    ManagedBy: "Karpenter"
    Environment: "Production"
    CostCenter: "PlatformEngineering"

2. The NodePool (Workload Scheduling & Lifecycle Spec)

The NodePool defines scheduling constraints, instance families, capacity types, and disruption budgets.

apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
  name: general-workloads
spec:
  template:
    spec:
      nodeClassRef:
        group: karpenter.k8s.aws
        kind: EC2NodeClass
        name: default-infrastructure
      
      requirements:
        # Prioritize Spot instances for 80% cost savings; allow fallback to on-demand
        - key: "karpenter.sh/capacity-type"
          operator: In
          values: ["spot", "on-demand"]
          
        # Multi-Architecture: Prioritize cost-efficient ARM64 Graviton, allow AMD64
        - key: "kubernetes.io/arch"
          operator: In
          values: ["arm64", "amd64"]
          
        # Select across diversified compute and general-purpose instance families
        - key: "karpenter.k8s.aws/instance-category"
          operator: In
          values: ["c", "m", "r"]
          
        # Generation: Use modern Graviton 3/4 and Intel/AMD 6th/7th gen
        - key: "karpenter.k8s.aws/instance-generation"
          operator: Gt
          values: ["5"]

  # Enterprise Disruption & Consolidation Guardrails
  disruption:
    consolidationPolicy: WhenUnderutilized
    consolidateAfter: 1m
    
    # 30-Day automated rolling node recycling for zero-touch security patching
    expireAfter: 720h
    
    # Prevent disruption storms during daytime traffic peaks
    budgets:
      - nodes: "10%" # Max 10% of nodes can be terminating simultaneously

๐Ÿ›ก๏ธ Protecting Workloads: PodDisruptionBudgets (PDBs)

When Karpenter consolidates nodes or handles a Spot interruption, it must drain running pods. Without a PodDisruptionBudget (PDB), Karpenter could terminate all replicas of a service simultaneously, causing an outage.

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: payment-service-pdb
  namespace: workloads
spec:
  # Guarantee that at least 2 pods are ALWAYS alive and handling traffic
  minAvailable: 2
  selector:
    matchLabels:
      app: payment-service

[!IMPORTANT] When a Spot interruption occurs, Karpenter will respect the PDB. However, if the 2-minute AWS deadline approaches and the PDB is still preventing drain, Karpenter will prioritize avoiding hard termination by force-evicting before AWS pulls the plug.


๐Ÿงญ Step-by-Step Operational Playbook: Deploying Karpenter & Testing Spot Interruption Draining

Follow this step-by-step runbook to deploy Karpenter v1, provision Graviton Spot nodes in under 45 seconds, and validate graceful Spot reclamation:

Step 1: Tag Subnets & Security Groups for Karpenter Discovery

  1. Plain-English Goal: Karpenter does not use fixed Node Groups; it discovers subnets and security groups dynamically using the karpenter.sh/discovery tag.
  2. Action:
    aws ec2 create-tags \
      --resources subnet-1a subnet-1b sg-eks-nodes \
      --tags "Key=karpenter.sh/discovery,Value=prod-eks"

Step 2: Apply the EC2NodeClass and Multi-Architecture NodePool

  1. Plain-English Goal: Allow Karpenter to choose across dozens of c6g, m6g, r6g, c6i, and m6i instance types (spot + on-demand) so Spot pool exhaustion in one family never halts scaling.
  2. Action:
    kubectl apply -f karpenter-ec2nodeclass.yaml
    kubectl apply -f karpenter-nodepool.yaml
    kubectl get nodepool,ec2nodeclass

Step 3: Trigger a Scale-Up Stress Test & Observe Fleet Bin-Packing

  1. Plain-English Goal: Scale a deployment from 0 to 50 replicas and watch Karpenter bypass Auto Scaling Groups to call ec2:RunInstances directly.
  2. Action:
    kubectl scale deployment inflate --replicas=50
    kubectl logs -n kube-system -l app.kubernetes.io/name=karpenter -f
    kubectl get nodeclaims -w

Step 4: Verify Spot Interruption Queue & PodDisruptionBudget (PDB) Protection

  1. Plain-English Goal: Ensure the SQS interruption queue is wired to EventBridge so 2-minute EC2 Spot termination warnings immediately cordon and drain nodes while respecting minAvailable PDBs.
  2. Action:
    aws sqs get-queue-attributes --queue-url "https://sqs.us-east-1.amazonaws.com/111122223333/prod-eks-interruption" --attribute-names All
    kubectl get pdb -A

๐Ÿ› ๏ธ Real-World Troubleshooting & Operational Failure Modes

1. โ€œKarpenter launches nodes, but Pods remain in Pending stateโ€

  • Symptom: EC2 instances boot and join the cluster, but the pending pods refuse to be scheduled on them.
  • Root Cause 1 - Taints and Tolerations: The NodePool applied a taint (e.g. dedicated=batch:NoSchedule), but the Pod deployment lacks the corresponding toleration.
  • Root Cause 2 - Missing Kubelet Resource Reservation: The Pod requests 4.0 CPU, and an instance with 4.0 CPU was launched. However, the kubelet and aws-node reserve 250m CPU for system overhead (kube-reserved), leaving only 3.75 CPU allocatable. The Pod cannot fit!
  • Fix: Always ensure Pod CPU/memory requests account for system overhead, or configure Karpenter to allow larger instances.

2. โ€œConsolidation Thrashing (Flapping)โ€

  • Symptom: Nodes are created, consolidated 2 minutes later, and then immediately recreated in an endless loop.
  • Root Cause: consolidateAfter is set too low (e.g., 0s), or application traffic fluctuates rapidly causing HPA to scale pods up and down every 60 seconds.
  • Fix: Set consolidateAfter: 1m or 5m, and configure disruption budgets to rate-limit node churn.

3. โ€œSubnet Discovery Failureโ€

  • Symptom: Karpenter logs show: no subnets found matching terms [{"tags":{"karpenter.sh/discovery":"my-cluster"}}].
  • Fix: Check your AWS VPC private subnets. Ensure the subnet tags include karpenter.sh/discovery = <cluster-name>.

๐Ÿ“ Knowledge Check & Real-World Interview Scenarios

โ“ Question 1: The Single-Instance Spot Trap

A junior engineer configures a Karpenter NodePool with capacity-type: ["spot"], but hardcodes instance-type: In ["c6g.xlarge"].

What operational disaster will happen when AWS experiences high demand for c6g.xlarge in that Availability Zone? How does an enterprise architect properly configure Spot NodePools?

โœ… Answer & Explanation

The Disaster: When AWS experiences high demand for c6g.xlarge, the Spot pool for that single instance family is exhausted. The AWS ec2:CreateFleet API call will fail with InsufficientInstanceCapacity. Because no other instance types were allowed, Karpenter cannot scale, pending pods will sit starved indefinitely, and the application will suffer a massive outage.

The Architectural Solution: Never hardcode a single instance type for Spot workloads! Enterprise architects practice Extreme Spot Diversification:

  • Specify broad categories (e.g., instance-category: In ["c", "m", "r"]).
  • Allow multiple instance generations (5, 6, 7).
  • Allow multiple sizes (xlarge, 2xlarge, 4xlarge).
  • This gives Karpenter a pool of 80+ distinct EC2 instance types across 3 Availability Zones, making capacity exhaustion virtually impossible.

โ“ Question 2: Karpenter Expiration vs. AMI Patching

In traditional Kubernetes clusters, updating the underlying node AMI to patch a zero-day Linux kernel vulnerability (like Dirty COW or Log4j) required engineers to run complex Terraform apply pipelines and manual node group rollouts.

How does Karpenterโ€™s expireAfter: 720h and dynamic AMI selection achieve Zero-Touch Automated Security Patching?

โœ… Answer & Explanation

The Mechanism:

  1. Dynamic AMI Selection: When the EC2NodeClass specifies amiFamily: AL2023 without a hardcoded AMI ID, Karpenter dynamically queries AWS SSM Parameter Store (/aws/service/eks/optimized-ami/...) for the latest AWS-recommended, patched AMI whenever launching a new instance.
  2. Continuous Rolling Renewal: The expireAfter: 720h (30 days) setting enforces that no node in the cluster can live longer than 30 days. Every day, approximately 3% of the clusterโ€™s nodes reach their expiration date.
  3. Graceful Drift Replacement: Karpenter automatically cordons the expiring node, provisions a fresh replacement node (which automatically pulls the newest patched AMI from AWS), drains pods gracefully according to PDBs, and terminates the old instance.
  4. The Result: The entire fleet is continuously, rollingly refreshed with the latest operating system security patches without a single line of Terraform change or manual engineer intervention!