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
| Aspect | ScaledObject | ScaledJob |
| Target | Deployment/StatefulSet | Job |
| Use case | Continuous throughput | Discrete tasks |
| Scale to zero | ✅ | ✅ (after completion) |
| Concurrency | Pool of replicas | One 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
| Category | Sources |
| Message Queues | Kafka, RabbitMQ, SQS, Azure Service Bus |
| Databases | PostgreSQL, MySQL, MongoDB |
| Cloud | AWS CloudWatch, Azure Monitor, GCP Pub/Sub |
| HTTP | HTTP endpoints |
| Metrics | Prometheus, 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
| Limitation | Impact |
| Node groups | Pre-defined instance types only |
| Slow scale-up | 3–4 minutes |
| No repacking | Doesn’t consolidate existing workloads |
| Request-based | Inflated requests look like real demand |
| GKE only option | On 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
| Dimension | Karpenter | Cluster Autoscaler |
| Provisioning | 45–60 seconds | 3–4 minutes |
| Instance selection | Any type (cheapest fitting) | Pre-defined node groups |
| Consolidation | ✅ Active repacking | ❌ Does not repack |
| Spot support | Native, automatic fallback | Separate ASGs, manual |
| GKE support | ❌ No official provider | ✅ Only option |
| AWS EKS | Default engine in EKS Auto Mode | Legacy |
| Azure AKS | GA in early 2026 | Legacy |
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
| Cloud | Notice Period |
| AWS | 2 minutes |
| Azure | 30 seconds |
| GCP | 30 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-Safe | Avoid Spot |
| Stateless web services | Single-instance databases |
| Batch processing jobs | Stateful apps without replication |
| CI/CD build agents | Real-time processing |
| Dev/test environments | Long-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
| Practice | Why |
| Diversify instance types | Reduces interruption frequency |
| Use multiple AZs | Capacity is regional |
| Set PDBs | Ensure availability during interruptions |
| Graceful shutdown | Handle 2-minute termination notice |
| Mix on-demand + spot | Fallback 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
| Layer | What It Does | When It Happens |
| Bin-packing | Scheduling decision | Pod placement time |
| Consolidation | Removes idle nodes | Ongoing |
Both layers are necessary for sustained cost reduction.
The Consolidation Engines
| Engine | How It Works |
| Karpenter | Active consolidation, direct cloud API |
| Cast AI Evictor | Evicts pods from underutilized nodes |
| Descheduler | Evicts pods violating policies |
10. Cost Monitoring Tools
Kubecost vs OpenCost
| Aspect | Kubecost | OpenCost |
| Launched | 2019 | 2022 |
| Acquired by | IBM (2024) | CNCF sandbox |
| Cost allocation | Any K8s concept | Any K8s concept |
| Multi-cluster | ✅ Yes | ✅ Yes |
| Cloud integration | AWS, Azure, GCP | AWS, Azure, GCP |
| Pricing | Freemium + Enterprise | Free |
| Best for | Enterprise cost management | Open-source cost visibility |
What Cost Tools Provide
| Feature | Description |
| Cost allocation | By namespace, deployment, label, team |
| Real-time monitoring | In-cluster + cloud costs |
| Optimization recommendations | Rightsizing, waste detection |
| Anomaly detection | Alert on spend spikes |
| Multi-cluster | Unified 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
- Deploys VPA in recommendation mode for all workloads
- Provides a dashboard showing recommendations
- 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
| Combination | Safe? | 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:
- HPA scales up → more replicas
- VPA sees lower per-pod usage → reduces requests
- HPA sees higher utilization → scales up more
- 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 Case | Example |
| DNS scaling | CoreDNS replicas scale with nodes |
| Ingress scaling | NGINX replicas scale with nodes |
| Monitoring | Prometheus 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.