Stage 10, Part 2 of 9, Autoscaling & Cost Optimization

Text

PART 2: ADVANCED CONCEPTS

5. KEDA

KEDA (Kubernetes Event-Driven Autoscaling) scales workloads based on external events — message queues, databases, HTTP endpoints — rather than just CPU/memory.

Why KEDA

Traditional HPA based on CPU and memory may respond too slowly for event-driven workloads such as offline jobs and streaming data. KEDA monitors event backlogs from sources such as message queues and databases, creates Jobs or Deployment replicas within seconds, and scales down to zero after tasks complete.

KEDA Architecture

text
Event Source (Kafka, RabbitMQ, SQS)
    │
    ▼
KEDA Scaler (periodic queries)
    │
    ▼
KEDA Operator
    │
    ▼
HPA (managed by KEDA)
    │
    ▼
Deployment / Job (scale replicas)

KEDA Example (ScaledObject)

yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: kafka-consumer
spec:
  scaleTargetRef:
    name: kafka-consumer
  minReplicaCount: 0          # Scale to zero!
  maxReplicaCount: 30
  triggers:
  - type: kafka
    metadata:
      bootstrapServers: kafka:9092
      consumerGroup: my-group
      topic: orders
      lagThreshold: "100"

KEDA Example (ScaledJob)

yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledJob
metadata:
  name: video-transcoder
spec:
  jobTargetRef:
    template:
      spec:
        containers:
        - name: transcoder
          image: transcoder:1.0
  triggers:
  - type: rabbitmq
    metadata:
      protocol: amqp
      queueName: video-jobs
      mode: QueueLength
      value: "5"
  maxReplicaCount: 10

ScaledJob vs ScaledObject

AspectScaledObjectScaledJob
TargetDeployment/StatefulSetJob
Use caseContinuous throughputDiscrete tasks
Scale to zero✅✅ (after completion)
ConcurrencyPool of replicasOne Job per event

Use ScaledJob when each event maps to a discrete, long-running task that runs to completion in its own pod. Use ScaledObject when events drive continuous throughput.

Supported Event Sources

CategorySources
Message QueuesKafka, RabbitMQ, SQS, Azure Service Bus
DatabasesPostgreSQL, MySQL, MongoDB
CloudAWS CloudWatch, Azure Monitor, GCP Pub/Sub
HTTPHTTP endpoints
MetricsPrometheus, Datadog

6. Cluster Autoscaler

The Cluster Autoscaler (CAS) scales the number of nodes in pre-defined node groups.

How CAS Works

CAS polls the Kubernetes API every 10 seconds. When it finds pods in a Pending state, it identifies which node group could accommodate them and triggers a scale-up event. The scale-up request goes to the cloud provider’s abstraction layer: an Auto Scaling Group on AWS, a Managed Instance Group on GCP, or a Virtual Machine Scale Set on Azure. The cloud provider spins up a node, Kubernetes registers it, and the scheduler places the pods. This roundtrip typically takes 3–4 minutes.

CAS Example

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cluster-autoscaler
  namespace: kube-system
spec:
  replicas: 1
  selector:
    matchLabels:
      app: cluster-autoscaler
  template:
    metadata:
      labels:
        app: cluster-autoscaler
    spec:
      serviceAccountName: cluster-autoscaler
      containers:
      - image: registry.k8s.io/autoscaling/cluster-autoscaler:v1.32.0
        name: cluster-autoscaler
        command:
        - ./cluster-autoscaler
        - --v=4
        - --cloud-provider=aws
        - --skip-nodes-with-local-storage=false
        - --expander=least-waste
        - --node-group-auto-discovery=asg:tag=k8s.io/cluster-autoscaler/enabled

CAS Limitations

LimitationImpact
Node groupsPre-defined instance types only
Slow scale-up3–4 minutes
No repackingDoesn’t consolidate existing workloads
Request-basedInflated requests look like real demand
GKE only optionOn GKE, CAS is still the only production option

7. Karpenter

Karpenter is the modern alternative to Cluster Autoscaler. It provisions cloud instances directly — no node groups, no intermediary ASG call, just a direct API request for the optimal instance type selected at scheduling time.

Karpenter vs Cluster Autoscaler

DimensionKarpenterCluster Autoscaler
Provisioning45–60 seconds3–4 minutes
Instance selectionAny type (cheapest fitting)Pre-defined node groups
Consolidation✅ Active repacking❌ Does not repack
Spot supportNative, automatic fallbackSeparate ASGs, manual
GKE support❌ No official provider✅ Only option
AWS EKSDefault engine in EKS Auto ModeLegacy
Azure AKSGA in early 2026Legacy

How Karpenter Works

text
Unschedulable Pod
    │
    ▼
Karpenter Controller (watches for pending pods)
    │
    ▼
Calculate optimal instance type (any type, cheapest)
    │
    ▼
Call cloud API directly (no ASG)
    │
    ▼
Node provisioned in 45-60 seconds
    │
    ▼
Pod scheduled

Karpenter NodePool Example

yaml
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
  name: default
spec:
  template:
    spec:
      requirements:
      - key: kubernetes.io/arch
        operator: In
        values: ["amd64"]
      - key: karpenter.sh/capacity-type
        operator: In
        values: ["spot", "on-demand"]
      - key: karpenter.k8s.aws/instance-family
        operator: In
        values: ["t3", "t3a", "t2"]
      nodeClassRef:
        name: default
  limits:
    cpu: 1000
    memory: 1000Gi
  disruption:
    consolidationPolicy: WhenUnderutilized
    expireAfter: 720h

The Consolidation Advantage

Karpenter actively consolidates running workloads onto fewer nodes. It identifies underutilized nodes, drains them, and deletes them — reducing node count without manual intervention. Cast AI Evictor cut node count by 50% in one measured case, keeping remaining nodes at 80% CPU utilization.


8. Spot Instances

Spot instances offer 60–90% discounts over on-demand instances. Cloud providers sell unused capacity at reduced rates with the caveat that instances can be reclaimed with short notice.

Spot Interruption Notice

CloudNotice Period
AWS2 minutes
Azure30 seconds
GCP30 seconds

The Golden Rule

Treat spot instances as ephemeral. Assume any spot instance can disappear at any moment. Design your architecture accordingly with automatic recovery and multi-instance redundancy.

Workload Classification

Spot-SafeAvoid Spot
Stateless web servicesSingle-instance databases
Batch processing jobsStateful apps without replication
CI/CD build agentsReal-time processing
Dev/test environmentsLong-running tasks without checkpointing

Spot Node Pool Example (AWS EKS)

yaml
apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig
metadata:
  name: production-cluster
  region: us-east-1
managedNodeGroups:
- name: spot-workers
  instanceTypes:
  - t3.large
  - t3a.large
  - t2.large
  spot: true
  minSize: 3
  maxSize: 20
  desiredCapacity: 5
  labels:
    node-lifecycle: spot
  taints:
  - key: spot-instance
    value: "true"
    effect: NoSchedule

Pod Tolerations for Spot

yaml
spec:
  tolerations:
  - key: spot-instance
    operator: Equal
    value: "true"
    effect: NoSchedule

Spot Best Practices

PracticeWhy
Diversify instance typesReduces interruption frequency
Use multiple AZsCapacity is regional
Set PDBsEnsure availability during interruptions
Graceful shutdownHandle 2-minute termination notice
Mix on-demand + spotFallback for critical workloads

9. Bin-Packing and Node Consolidation

Bin-packing places pods densely on fewer nodes, reducing idle node cost.

Why the Default Scheduler Doesn't Pack

The default scoring plugin is NodeResourcesFit with a LeastAllocated strategy. This scores nodes higher when they have more free capacity, spreading pods thin across many nodes each running at low utilization.

Switching to MostAllocated

yaml
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: default-scheduler
  pluginConfig:
  - name: NodeResourcesFit
    args:
      scoringStrategy:
        type: MostAllocated
        resources:
        - name: cpu
          weight: 1
        - name: memory
          weight: 1

The Two Layers

LayerWhat It DoesWhen It Happens
Bin-packingScheduling decisionPod placement time
ConsolidationRemoves idle nodesOngoing

Both layers are necessary for sustained cost reduction.

The Consolidation Engines

EngineHow It Works
KarpenterActive consolidation, direct cloud API
Cast AI EvictorEvicts pods from underutilized nodes
DeschedulerEvicts pods violating policies

10. Cost Monitoring Tools

Kubecost vs OpenCost

AspectKubecostOpenCost
Launched20192022
Acquired byIBM (2024)CNCF sandbox
Cost allocationAny K8s conceptAny K8s concept
Multi-cluster✅ Yes✅ Yes
Cloud integrationAWS, Azure, GCPAWS, Azure, GCP
PricingFreemium + EnterpriseFree
Best forEnterprise cost managementOpen-source cost visibility

What Cost Tools Provide

FeatureDescription
Cost allocationBy namespace, deployment, label, team
Real-time monitoringIn-cluster + cloud costs
Optimization recommendationsRightsizing, waste detection
Anomaly detectionAlert on spend spikes
Multi-clusterUnified view

Installing Kubecost

bash
helm repo add kubecost https://kubecost.github.io/cost-analyzer/
helm install kubecost kubecost/cost-analyzer \
  --namespace kubecost --create-namespace \
  --set kubecostToken="<token>"

11. Rightsizing and Goldilocks

Goldilocks is a tool that provides VPA recommendations in a dashboard.

How Goldilocks Works

  1. Deploys VPA in recommendation mode for all workloads
  2. Provides a dashboard showing recommendations
  3. Helps teams right-size without manual analysis

Goldilocks Architecture

text
Goldilocks Controller
    │
    ▼
Creates VPA objects for each workload
    │
    ▼
VPA Recommender generates recommendations
    │
    ▼
Goldilocks Dashboard shows recommendations

Installing Goldilocks

bash
helm repo add fairwinds-stable https://charts.fairwinds.com/stable
helm install goldilocks fairwinds-stable/goldilocks \
  --namespace goldilocks --create-namespace

12. HPA + VPA + KEDA Coordination

The three autoscalers must work together, not against each other.

The Coordination Matrix

CombinationSafe?Notes
HPA (CPU) + VPA (memory)✅Different resources
HPA (CPU) + VPA (Auto)❌They fight
HPA (CPU) + VPA (Off)✅Recommendations only
KEDA + HPA✅KEDA manages HPA
KEDA + VPA✅Different scaling dimensions

The Recommended Architecture

text
HPA → scales replicas based on CPU/custom metrics
VPA (Off) → recommends requests for right-sizing
KEDA → scales based on external events (queues, databases)
Karpenter → provisions nodes for unschedulable pods

The Death Spiral

When HPA and VPA both act on CPU:

  1. HPA scales up → more replicas
  2. VPA sees lower per-pod usage → reduces requests
  3. HPA sees higher utilization → scales up more
  4. Repeat → unstable replica count

Prevention: Never run VPA Auto alongside HPA on the same CPU metric.


13. Cluster Proportional Autoscaler

The Cluster Proportional Autoscaler (CPA) scales workloads proportionally to cluster size (number of nodes or cores).

When to Use CPA

Use CaseExample
DNS scalingCoreDNS replicas scale with nodes
Ingress scalingNGINX replicas scale with nodes
MonitoringPrometheus replicas scale with nodes

CPA Example

yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: coredns
  namespace: kube-system
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: coredns
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: External
    external:
      metric:
        name: cluster_cores
      target:
        type: AverageValue
        averageValue: "256"

1:1 copy of the class Google Doc, code in code blocks.