Stage 10, Part 1 of 9 · p. 83, Autoscaling & Cost Optimization

PART 1: CORE THEORY

1. The Kubernetes Cost Problem

Kubernetes is designed for availability, not cost efficiency. The default scheduler spreads pods across nodes to reduce blast radius when a node fails. This is a reasonable availability decision—and it directly conflicts with cost efficiency. The result: most clusters run at 20–30% actual utilization, meaning overprovisioning that costs three to five times the compute needed.

The Numbers

MetricValueSource
Clusters over-provisioning CPU69% (up from 40% two years prior)Cast AI 2026 State of Kubernetes report
Average CPU utilization8%Cast AI 2026
Container costs going to idle resources83%Datadog
Mid-sized platform team waste$45,000+ per monthZesty

Why Defaults Waste Money

Default BehaviorCost Impact
LeastAllocated scoringSpreads pods, leaves nodes underutilized
Resource requests ignoredScheduler uses requests, not actual usage
No consolidationIdle nodes stay running
No spot integrationPay full on-demand price
No cost visibilityCan't optimize what you can't see

The Three Levers

LeverToolImpact
RightsizingVPA, GoldilocksMatch requests to actual usage
ScalingHPA, KEDAMatch replicas to demand
PlacementBin-packing, KarpenterPack workloads densely
PricingSpot instancesPay less for the same compute

2. Resource Requests and Limits

Resource management is the foundation of cost optimization. Getting it wrong causes both waste and reliability issues.

The Three Numbers

NumberMeaningUsed By
RequestMinimum resources guaranteedScheduler
LimitMaximum resources allowedKernel (cgroups)
Actual usageWhat the workload really consumesMonitoring

The gap between these three numbers is where cost and reliability problems show up.

The Cost Impact

ScenarioRequestActualWaste
Over-requested2 CPU200m90% waste
Under-requested100m500mThrottling, OOMKills
Right-sized300m250mMinimal waste

The Scheduler's Perspective

The scheduler operates on requests, not actual usage. A Pod requesting 2 CPUs but using 200m is treated as a 2-CPU Pod during scheduling. A cluster with 8% actual CPU utilization can still appear “busy” to the autoscaler because inflated resource requests look like real demand.

QoS Classes and Cost

QoSRequests vs LimitsEviction PriorityCost
Guaranteedrequests == limitsLastHighest
Burstablerequests < limitsMiddleMedium
BestEffortNo requests/limitsFirstLowest

3. Horizontal Pod Autoscaler

The Horizontal Pod Autoscaler (HPA) scales the number of Pod replicas based on observed metrics.

How HPA Works

text
HPA Controller (every 15s)
    │
    ▼
Read metrics (CPU, memory, custom)
    │
    ▼
Calculate desired replicas:
  desiredReplicas = ceil(currentReplicas × (currentMetric / targetMetric))
    │
    ▼
Scale Deployment/ReplicaSet

HPA Example

yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web
  minReplicas: 2
  maxReplicas: 20
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
      - type: Percent
        value: 100
        periodSeconds: 15
      - type: Pods
        value: 4
        periodSeconds: 15
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
      - type: Percent
        value: 25
        periodSeconds: 60

HPA Best Practices 2026

PracticeWhy
Set appropriate stabilization windowsPrevent thrashing
Use behavior policiesControl scale-up/down speed
Combine with VPA for right-sized podsEnsure requests are accurate
Monitor HPA decisionskubectl describe hpa

The Behavior Block

The behavior block is critical for production. A common pattern: scale up fast (100% in 15 seconds) and scale down slowly (25% per minute with a 5-minute stabilization window).

HPA Limitations

LimitationImpact
CPU-based only (default)Doesn't work for queue-based workloads
Reacts to metrics15-second interval; not instantaneous
No scale-to-zeroMinimum replicas must be ≥ 1
Conflicts with VPAIf both use CPU metrics

4. Vertical Pod Autoscaler

The Vertical Pod Autoscaler (VPA) adjusts the CPU and memory requests/limits of Pods.

How VPA Works

text
VPA Recommender
    │
    ▼
Analyze historical usage
    │
    ▼
Generate recommendations (lower, target, upper)
    │
    ▼
VPA Updater (if Auto mode)
    │
    ▼
Evict and recreate Pods with new requests

VPA Example

yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: web-vpa
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web
  updatePolicy:
    updateMode: "Auto"       # Off, Initial, Auto
  resourcePolicy:
    containerPolicies:
    - containerName: '*'
      minAllowed:
        cpu: 100m
        memory: 128Mi
      maxAllowed:
        cpu: 4
        memory: 8Gi

VPA Update Modes

ModeBehavior
OffRecommendations only (no changes)
InitialSet requests on Pod creation
AutoEvict and recreate Pods to apply

VPA Best Practices

PracticeWhy
Run in recommendation mode for 7 daysGet accurate data
Never run VPA Auto alongside HPA on the same CPU metricThey will fight each other
Use VPA for memory right-sizingMemory is less variable than CPU
Set min/max boundsPrevent extreme recommendations

The VPA + HPA Conflict

HPA and VPA conflict when resource requests change, creating unstable replica counts and the Kubernetes “death spiral”. VPA’s histograms get polluted when HPA scales.

Solution: Use VPA for memory only, HPA for CPU. Or use VPA in recommendation mode only.


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