Kubernetes Autoscaling & Resiliency
Deep dive into Kubernetes autoscaling: Horizontal Pod Autoscaler (HPA), Vertical Pod Autoscaler (VPA), Cluster Autoscaler, and PodDisruptionBudgets.
Imagine running an online ticket platform. On a regular Tuesday morning, your website handles around 50 visitors browsing movie showtimes. A few small container pods easily manage the traffic. Then, at 11:00 AM, tickets for a major world concert tour go on sale. Within seconds, hundreds of thousands of fans arrive at once. If your infrastructure cannot scale dynamically, CPU usage hits 100%, memory runs out, containers crash, and buyers encounter error screens. Kubernetes Autoscaling provides the flexibility needed to handle sudden traffic spikes as well as quiet overnight periods. By scaling at both the application level (adding more pods) and the infrastructure level (adding more cloud servers), Kubernetes ensures services stay available under heavy load without wasting money on idle servers during quiet hours.
Definition
Kubernetes Autoscaling is the automated process of adjusting compute resources (horizontally by changing pod counts, vertically by adjusting pod CPU and memory sizing, or infrastructurally by adding worker nodes) in response to live workload demand.
Why It Matters
Manual scaling cannot respond fast enough to real-world traffic surges. By the time an engineer receives an alert, logs into a cloud portal, and spins up extra servers, users have already experienced downtime. Kubernetes autoscaling matches infrastructure capacity with actual user demand. During peak hours, it scales up to keep response times low; during quiet periods, it scales down, helping organizations reduce their cloud hosting costs significantly.
How It Works
Kubernetes provides three coordinated layers of autoscaling, alongside event-driven tools: 1. Horizontal Pod Autoscaler (HPA: Workload Scaling): HPA adjusts the number of running pod replicas based on real-time metrics: • Standard Metrics: Average CPU or memory usage reported by `metrics-server` (such as maintaining 70% CPU usage across pods). • Custom Metrics: Application-specific metrics from Prometheus (such as requests per second or message queue depth). • Formula: `desiredReplicas = ceil[ currentReplicas * ( currentMetricValue / desiredMetricValue ) ]`. 2. Vertical Pod Autoscaler (VPA: Sizing Optimization): VPA analyzes historical usage and automatically adjusts the CPU and memory limits of individual pods. This is particularly helpful for applications that cannot easily scale horizontally into multiple parallel copies. 3. Cluster Autoscaler / Karpenter (Infrastructure Scaling): When HPA scales a deployment from 5 to 50 pods, existing worker nodes might run out of capacity, leaving new pods in a 'Pending' state. The Cluster Autoscaler detects these pending pods and automatically provisions new cloud servers (such as AWS EC2 or Google Cloud compute instances). When traffic declines and nodes become underutilized, it safely moves pods and terminates unneeded servers. 4. KEDA (Kubernetes Event-Driven Autoscaling): An open-source tool that allows pods to scale based on external events (such as messages in RabbitMQ, Kafka, or AWS SQS), including scaling deployments down to zero when queues are empty. 5. PodDisruptionBudgets (PDB): Ensures high availability during voluntary maintenance (such as draining nodes for software upgrades). A PDB specifies that a minimum percentage of pods (such as 80%) must always remain online.
The Three Layers of Kubernetes Autoscaling
Key Points
- HPA requires `resources.requests` to be defined on your containers in order to calculate percentages.
- HPA scales pods (application level); the Cluster Autoscaler scales worker nodes (infrastructure level).
- KEDA enables event-driven scaling down to zero pods when queues are empty, saving significant cloud costs.
- Configure stabilization windows to avoid 'flapping' (rapid, repeated scaling up and down).
- PodDisruptionBudgets protect your application availability during planned cluster maintenance and node upgrades.
Steps
Install the Metrics Server
Deploy `metrics-server` to your cluster so `kubectl top pods` and the HPA can read CPU and memory usage.
Set Resource Requests on All Pods
HPA calculations rely on percentage utilization of requested resources; ensure `resources.requests.cpu` is declared on all containers.
Create an HPA Manifest
Define minimum and maximum replica bounds along with target metric percentages in an HPA YAML file.
Add a PodDisruptionBudget (PDB)
Set a PDB (`minAvailable: 2`) so node maintenance operations do not take down all instances of your service at once.
Test Under Load and Verify Scale-Down
Run load tests using tools like k6 to verify that pods scale up under stress and scale back down smoothly once traffic drops.
Examples
The Bank Teller and Branch Analogy
When three customers enter a bank, two tellers handle them comfortably. When fifty customers arrive at once, the manager opens four more teller windows (HPA: adding pods). If the lobby runs completely out of room, the bank opens a second branch building down the street (Cluster Autoscaler: adding worker nodes).
Real-World Examples
E-Commerce Holiday Traffic Management
During major holiday shopping sales, e-commerce platforms experience surges of tens of thousands of transactions per minute. By leveraging Kubernetes Horizontal Pod Autoscaling and automated node provisioning, systems scale from hundreds of pods to thousands of pods automatically, absorbing peak checkout traffic without manual intervention.
Technical Examples
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: checkout-api-hpa
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: checkout-api
minReplicas: 3
maxReplicas: 30
metrics:
# Target 70% average CPU usage across pods
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
# Target 80% average memory usage
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
# Prevent rapid oscillations (flapping)
behavior:
scaleUp:
stabilizationWindowSeconds: 0 # Scale up quickly when traffic surges
policies:
- type: Percent
value: 100
periodSeconds: 15
scaleDown:
stabilizationWindowSeconds: 300 # Wait 5 minutes of low load before scaling down
policies:
- type: Percent
value: 10
periodSeconds: 60
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: checkout-api-pdb
namespace: production
spec:
minAvailable: 2 # Keep at least 2 pods running during node maintenance
selector:
matchLabels:
app: checkout-apiHorizontal Pod Autoscaler (HPA) vs Vertical Pod Autoscaler (VPA)
| Aspect | Horizontal Pod Autoscaler (HPA) | Vertical Pod Autoscaler (VPA) |
|---|---|---|
| Scaling Approach | Adds or removes Pod replicas | Adjusts CPU and memory allocations per Pod |
| Best Workloads | Stateless applications and web microservices | Stateful services, databases, and batch jobs |
| Impact on Traffic | Zero downtime: adds parallel pods smoothly | May require restarting pods to apply new memory limits |
| Scale to Zero | Supported using KEDA event triggers | Not applicable: pods always require baseline resources |
Quality of Service (QoS) Classes
Advantages
- Cost Efficiency: Pay only for the computing power needed to handle active traffic.
- Reliability Under Load: Automatically absorbs sudden surges without manual configuration.
- Safer Maintenance: PodDisruptionBudgets ensure planned cluster updates do not disrupt user availability.
Limitations
- Cloud Provisioning Time: Spinning up brand-new cloud virtual machines can take a few minutes (though tools like Karpenter speed this up).
- Avoid Metric Conflicts: Do not configure HPA and VPA to manage the same resource metrics on the same deployment at the same time.
Interview Questions
How do HPA, Cluster Autoscaler, and PodDisruptionBudgets work together?
During traffic surges, the Horizontal Pod Autoscaler (HPA) adds more pod replicas. If worker nodes run out of space, the new pods sit in a pending state until the Cluster Autoscaler requests additional cloud servers. Once those servers join the cluster, the pods start running. Meanwhile, a PodDisruptionBudget (PDB) ensures that during planned cluster maintenance or node draining, a minimum number of healthy pods remain online so service is not interrupted.
Practice Questions
- Deploy a HorizontalPodAutoscaler on a test service and run a simple load test to observe replicas scaling up.
- Check a pod's QoS class with `kubectl get pod <pod-name> -o jsonpath='{.status.qosClass}'`.
