In modern cloud-native architectures, static resource allocation often leads to either unnecessary cost overruns or performance bottlenecks. The solution lies in dynamic scaling, specifically using Horizontal Pod Autoscalers (HPA). This article guides you through a practical exercise configuring an HPA in Azure Kubernetes Service (AKS) based on CPU metrics. Whether you are an IT student setting up your first lab, a junior engineer preparing for certification, or a practitioner optimizing production workloads, understanding the mechanics of autoscaling is essential for efficient infrastructure management.
This guide assumes a standard AKS environment running Kubernetes 1.28 or later. It does not provide financial or legal advice regarding cloud pricing; costs depend on your specific node pool sizes, region, and usage patterns. Always verify current Azure pricing in the official documentation before making budget decisions.
Understanding Horizontal Pod Autoscaling Mechanisms
Before writing any code, it is crucial to understand how the HPA operates within the control plane. The Horizontal Pod Autoscaler is a controller that automatically adjusts the number of replicas for a deployment, replica set, or stateful set. It does this by monitoring resource usage metrics, such as CPU utilization or memory consumption.
The core logic follows a simple feedback loop:
1. Observation: The HPA queries the Kubernetes Metrics Server to gather current metric data (e.g., average CPU usage per pod).
2. Calculation: It compares the observed metrics against a target percentage defined in the configuration.
3. Action: If the actual usage exceeds the target, the HPA increases the replica count. If usage drops significantly, it decreases the count to save costs.
It is important to note that scaling decisions are made independently for each pod group managed by the HPA. The scaling range must be defined by a minReplicas and maxReplicas setting. Additionally, the underlying node pool must have sufficient capacity to accommodate new pods; if nodes are full, the HPA will attempt to scale out but may fail if no space exists, leading to “Desired Replicas” remaining less than “Current Replicas.”
Prerequisites and Lab Environment Setup
To perform this exercise safely, you need a functional AKS cluster. This guide uses a hypothetical lab scenario where we create a default namespace and deploy a sample workload. For production environments, ensure your network security groups (NSGs) allow traffic on port 443 for the metrics server and that the Metrics Server add-on is installed in your control plane or agent pool.
Required Components:
* An AKS cluster with at least one System Pool or User-defined Node Pool.
* The kubectl command-line tool installed and configured with credentials to your Azure subscription.
* Helm (optional, though we will use native YAML for clarity).
* Access to the Azure portal or CLI.
Safety Note: Always test scaling configurations in a non-production environment first. Scaling policies that are too aggressive can cause “thrashing,” where pods are constantly created and destroyed, leading to high latency and potential instability.
Step-by-Step Configuration of the HPA
We will now configure an HPA for a sample web application deployment. This example sets the target CPU utilization to 70%. If the average CPU usage across all pods in the deployment exceeds 70%, the system will add new pods up to a maximum of 5 replicas.
First, create a simple Deployment named sample-app with a fixed number of replicas for testing purposes:
apiVersion: apps/v1
kind: Deployment
metadata:
name: sample-app
namespace: default
spec:
replicas: 2
selector:
matchLabels:
app: sample-app
template:
metadata:
labels:
app: sample-app
spec:
containers:
- name: nginx
image: nginx:1.24-alpine
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "256Mi"
Apply this configuration using kubectl apply -f deployment.yaml. Next, we define the Horizontal Pod Autoscaler. This YAML file specifies the target CPU percentage and the scaling range:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: sample-app-hpa
namespace: default
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: sample-app
minReplicas: 2
maxReplicas: 5
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
Apply the HPA configuration with kubectl apply -f hpa.yaml. The averageUtilization metric calculates the average CPU usage per pod relative to its requested CPU resources. If a pod requests 100m (0.1 cores) and uses 70m, that is considered 70% utilization.
Verification and Monitoring Scaling Events
After applying the configuration, you must verify that the HPA is active and responding correctly. Use the following command to check the status:
kubectl get hpa sample-app-hpa -n default
Expected Output Illustration:
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS
sample-app-hpa Deployment/sample-app 0%/70% 2 5 2
In this state, the TARGETS column shows 0%, indicating that current CPU usage is well below the 70% threshold, so no scaling has occurred yet. To trigger a scale-out event in your lab environment, you can simulate high load. One practical method for students is to deploy a script that generates traffic (e.g., using hey or ab tools) against the application endpoints until CPU usage spikes.
Alternatively, you can inspect the live metrics:
kubectl top pods -n default --selector app=sample-app
If you observe that the average CPU usage across the selected pods exceeds 70%, the HPA controller will initiate a scaling event. You can watch the scale-up in real-time using:
kubectl get hpa sample-app-hpa -w -n default
Illustrative Output During Scaling:
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
sample-app-hpa Deployment/sample-app 71%/70% 2 5 3 5m
Notice how the REPLICAS count increased to 3 because the observed load crossed the threshold. Once the new pods stabilize and CPU usage drops below the target (or if you manually stop the load), the HPA may scale back down, provided it hasn’t hit the minReplicas limit.
Common Errors and Troubleshooting Scenarios
Even in safe lab environments, specific errors can occur. Understanding these helps in debugging production issues.
Error 1: “No metrics found”
If you see an error stating that no metrics are available, the Metrics Server is likely not running or failing to scrape data from the node API server. This is a common issue if the add-on was not installed during cluster creation.
* Fix: Verify the Metrics Server status with kubectl get pods -n kube-system | grep metrics-server. If missing, install it using the Azure documentation scripts or Helm charts.
Error 2: “Desired Replicas is less than Current Replicas”
This occurs when the HPA tries to scale down, but the node pool is full, or there are pending pods waiting for resources. The controller cannot remove a pod if another one cannot yet be scheduled.
* Fix: Scale out your underlying node pool (e.g., increase the maxPods limit or add more VMs) to provide scheduling headroom.
Error 3: Scaling Lag
HPA does not scale instantly. It polls metrics every 15 seconds by default. If you generate a spike in traffic for only 5 seconds, the HPA might not see it and won’t scale up.
* Fix: Ensure your load testing duration is long enough (e.g., at least 30-60 seconds) to trigger a scaling event.
Industry Application and Cost Control Considerations
In a real-world industry application, such as an e-commerce platform during a flash sale, the HPA ensures that customer experience remains high by adding capacity automatically. However, cost control is equally vital. Over-provisioning maxReplicas can lead to wasted spend if traffic drops rapidly after the event.
A best practice for cost optimization is to use a combination of metrics. While CPU is standard, memory or custom application metrics (like request latency) might be more accurate indicators of stress. You can configure multiple metrics in the HPA spec:
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
Practical Student Task:
Set up a local AKS lab (using Azure Free Tier or a small pay-as-you-go cluster). Deploy a simple web app. Write a script that sends increasing amounts of requests every minute for 10 minutes. Observe how the HPA scales up and down. Record the number of pods created and estimate the cost impact compared to a static deployment with double the initial pod count. This exercise solidifies the concept of paying only for what you use.
Conclusion
Configuring Horizontal Pod Autoscalers in AKS based on CPU metrics is a fundamental skill for any cloud engineer. By following the steps outlined above, you can create a resilient infrastructure that adapts to demand automatically. Remember to verify your Metrics Server installation, define appropriate scaling ranges to avoid thrashing, and always test scaling policies in a safe environment before deploying them to critical production workloads. Always consult official Azure documentation for the latest version-specific details and security best practices.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

