Apply Now Apply Now Apply Now
header_logo
Post thumbnail
DEVOPS

Kubernetes HPA Tutorial: Automatically Scale Applications Based on Demand

By Vishalini Devarajan

Modern applications experience changing workloads throughout the day. An e-commerce application may receive thousands of requests during a sale, while traffic remains low during regular hours. Running the same number of application instances throughout these periods can waste resources or affect application performance.

Kubernetes HPA (Horizontal Pod Autoscaler) helps solve this problem by automatically increasing or decreasing the number of Pods based on resource utilisation or other configured metrics. It allows applications to handle changing workloads without requiring developers to manually adjust replica counts.

In this tutorial, you will learn how Kubernetes HPA works, its prerequisites, how to configure autoscaling using YAML and kubectl commands, and how to troubleshoot common scaling issues.

Table of contents


  1. TL;DR
  2. What Is Kubernetes HPA (Horizontal Pod Autoscaler)?
  3. How Does Horizontal Pod Autoscaler Work in Kubernetes?
  4. Kubernetes HPA Prerequisites
  5. Kubernetes HPA Tutorial: Step-by-Step Implementation
    • Step 1: Create a Kubernetes Deployment
    • Step 2: Expose the Application Using a Service
    • Step 3: Create a Kubernetes HPA
    • Step 4: Check HPA Status
    • Step 5: Generate Traffic to Trigger Scaling
    • Step 6: Configure HPA Using YAML
  6. Kubernetes HPA Metrics and Scaling Targets
  7. Kubernetes HPA vs VPA: What Is the Difference?
  8. Kubernetes HPA Best Practices
  9. Common Kubernetes HPA Issues and Troubleshooting
  10. Conclusion
  11. Frequently Asked Questions (FAQs)
    • What is Kubernetes HPA used for?
    • How does Horizontal Pod Autoscaler work in Kubernetes?
    • What metrics does Kubernetes HPA use?
    • What is the difference between HPA and VPA in Kubernetes?

TL;DR

  • Kubernetes HPA automatically increases or decreases the number of Pod replicas based on application demand.
  • It uses CPU, memory, custom, or external metrics to determine when scaling is required.
  • Metrics Server provides CPU and memory metrics required for resource-based autoscaling.
  • The autoscaling/v2 API supports multiple metrics and configurable scaling behaviour.
  • HPA manages Pod replicas, while solutions such as Cluster Autoscaler manage Kubernetes worker nodes.

What Is Kubernetes HPA (Horizontal Pod Autoscaler)?

Kubernetes HPA is a built-in autoscaling mechanism that automatically adjusts the number of running Pod replicas based on observed resource utilisation or other configured metrics.

It helps applications handle changing workloads by scaling horizontally. Instead of increasing the CPU or memory allocated to an existing Pod, HPA creates additional Pods when demand increases and reduces their number when demand decreases.

For example, consider an online shopping application running three Pods. During a promotional sale, incoming requests increase and CPU utilisation rises. Kubernetes HPA detects the higher utilisation and increases the number of replicas to handle the additional traffic.

When traffic decreases, HPA gradually reduces the replicas, subject to its configured scaling behaviour and minimum replica count.

The main benefits include:

  • Improved availability: Additional Pods help applications handle increased workloads.
  • Resource efficiency: Unnecessary replicas can be removed when demand decreases.
  • Reduced manual work: Developers do not need to continuously adjust replica counts.
  • Better scalability: Applications can respond to changing traffic more effectively.

How Does Horizontal Pod Autoscaler Work in Kubernetes?

Horizontal Pod Autoscaler Kubernetes uses a control loop to monitor application metrics, calculate the required number of replicas, and update the target workload.

The process involves five main steps:

  1. Metric collection: Kubernetes collects CPU, memory, or configured application metrics from running Pods.
  2. Metric availability: Metrics Server or an appropriate metrics adapter exposes the required metrics through Kubernetes APIs.
  3. Metric comparison: The HPA controller compares current metric values against the configured target.
  4. Replica calculation: It calculates how many replicas are required to reach the target utilisation.
  5. Workload scaling: The controller updates the Deployment’s desired replica count, and Kubernetes creates or removes Pods accordingly.

For example, suppose an application has four replicas, with an average CPU utilisation of 80%. Its HPA target is 40%.

The simplified scaling calculation is:

Desired Replicas = Current Replicas × (Current Utilisation / Target Utilisation)

= 4 × (80 / 40)

= 8 Replicas

Kubernetes may therefore increase the desired replica count to eight, subject to scaling limits and other controller checks.

Want to build practical DevOps skills? Explore the HCL GUVI DevOps course to learn essential DevOps tools, containerisation, Kubernetes, CI/CD, and deployment practices through structured learning and hands-on projects.

What is the role of Metrics Server?

Metrics Server collects CPU and memory usage information from Kubernetes nodes through their kubelets and exposes it through the Metrics API.

The HPA controller uses these metrics to make scaling decisions. The controller runs as part of the Kubernetes control plane and periodically evaluates the configured scaling targets.

Metrics Server is designed for autoscaling and basic resource metrics. It is not a replacement for full monitoring solutions.

Kubernetes HPA Prerequisites

Before configuring Kubernetes autoscaling, ensure that your cluster meets the following requirements:

PrerequisitePurpose
Running Kubernetes clusterProvides the environment to deploy and manage applications.
Deployment or scalable workloadProvides the Pods that HPA will scale.
Resource requestsRequired for CPU and memory utilisation-based scaling.
Metrics ServerSupplies CPU and memory metrics through the Metrics API.
Kubernetes permissionsAllows you to create and manage HPA resources.

You can check whether Metrics Server is providing resource metrics using:

kubectl top nodes

kubectl top pods

If these commands return resource usage information, the Metrics API is available.

If Metrics Server is not installed, install a compatible release by following its official deployment instructions:

Kubernetes Metrics Server installation guide.

Kubernetes HPA Tutorial: Step-by-Step Implementation

Let’s implement Kubernetes HPA using a sample NGINX application. You will create a Deployment, expose it through a Service, configure autoscaling, and generate traffic to observe how the replica count changes.

Step 1: Create a Kubernetes Deployment

First, create a Deployment with two NGINX replicas.

Create a file named nginx-deployment.yaml:

apiVersion: apps/v1

kind: Deployment

metadata:

  name: nginx-deployment

spec:

  replicas: 2

  selector:

    matchLabels:

      app: nginx

  template:

    metadata:

      labels:

        app: nginx

    spec:

      containers:

      - name: nginx

        image: nginx:1.27

        ports:

        - containerPort: 80

        resources:

          requests:

            cpu: 100m

            memory: 64Mi

          limits:

            cpu: 500m

            memory: 128Mi

Here:

  • replicas: 2 starts two application Pods.
  • requests specifies the CPU and memory resources requested by each container.
  • limits defines the maximum CPU and memory resources available to each container.

Apply the configuration:

kubectl apply -f nginx-deployment.yaml

Verify the Deployment:

kubectl get deployments

kubectl get pods

Step 2: Expose the Application Using a Service

Create a Service to expose the NGINX application inside the cluster.

kubectl expose deployment nginx-deployment \

  --name=nginx-service \

  --port=80 \

  --target-port=80 \

  --type=ClusterIP

Check whether the Service is running:

kubectl get services

The Service provides a stable network endpoint for accessing the application, even when HPA changes the number of Pods.

Step 3: Create a Kubernetes HPA

Now, configure HPA to maintain CPU utilisation around 50%.

Run:

kubectl autoscale deployment nginx-deployment \

  --cpu-percent=50 \

  --min=2 \

  --max=10

This command creates an HPA with the following configuration:

  • Minimum replicas: 2
  • Maximum replicas: 10
  • Target CPU utilisation: 50%

Kubernetes will monitor CPU utilisation and adjust the Deployment’s replica count when scaling is required.

Step 4: Check HPA Status

Use the following command:

kubectl get hpa

Example output:

NAME               REFERENCE

nginx-deployment   Deployment/nginx-deployment

TARGETS     MINPODS   MAXPODS   REPLICAS

25%/50%     2         10        2

The 25%/50% value indicates that the current average CPU utilisation is 25%, against a target of 50%.

You can also inspect additional information using:

kubectl describe hpa nginx-deployment

This command displays current metrics, scaling events, replica counts, and possible errors.

Step 5: Generate Traffic to Trigger Scaling

To observe autoscaling, generate traffic against the NGINX application.

Run a temporary BusyBox Pod:

kubectl run load-generator \

  --image=busybox:1.36 \

  --restart=Never \

  -- /bin/sh -c \

  "while true; do wget -q -O- http://nginx-service; done"

This command continuously sends requests to the NGINX Service.

In another terminal, monitor the HPA:

kubectl get hpa nginx-deployment --watch

You can also monitor the Pods:

kubectl get pods --watch

If the workload increases CPU utilisation above the configured target, HPA may increase the number of replicas.

Note: A continuous HTTP request loop does not guarantee that CPU utilisation will reach 50%. The actual scaling response depends on the workload, available resources, metrics collection, and scaling policies.

GUVI Ad

After testing, stop the load generator and remove it:

kubectl delete pod load-generator

As application demand decreases, HPA can reduce the number of replicas until the configured minimum is reached.

Step 6: Configure HPA Using YAML

You can also define HPA using a Kubernetes YAML manifest. The autoscaling/v2 API is recommended because it supports multiple metrics and configurable scaling behaviour.

Create a file named nginx-hpa.yaml:

apiVersion: autoscaling/v2

kind: HorizontalPodAutoscaler

metadata:

  name: nginx-hpa

spec:

  scaleTargetRef:

    apiVersion: apps/v1

    kind: Deployment

    name: nginx-deployment

  minReplicas: 2

  maxReplicas: 10

  metrics:

  - type: Resource

    resource:

      name: cpu

      target:

        type: Utilization

        averageUtilization: 50

  behavior:

    scaleDown:

      stabilizationWindowSeconds: 300

This configuration:

  • Targets the nginx-deployment Deployment.
  • Maintains between two and ten replicas.
  • Targets average CPU utilisation of 50%.
  • Uses a five-minute scale-down stabilization window to reduce unnecessary fluctuations.

Apply the configuration:

kubectl apply -f nginx-hpa.yaml

Check the configuration:

kubectl get hpa

kubectl describe hpa nginx-hpa

Use either the command-based HPA or the YAML-based HPA for this Deployment, rather than creating two competing autoscalers for the same workload.

Also checkout: Kubernetes Roadmap 2026: How to Learn Kubernetes Step by Step for a Successful DevOps Career

Kubernetes HPA Metrics and Scaling Targets

Kubernetes HPA supports different metric types to determine when an application needs additional resources.

Metric typeWhat it measuresExample
CPU utilisationAverage CPU usage relative to requested CPUScale when CPU utilisation exceeds 60%.
Memory utilisationAverage memory usage relative to requested memoryScale when memory utilisation exceeds 70%.
Custom metricsApplication-specific metricsScale based on requests processed per second.
External metricsMetrics from systems outside the Kubernetes workloadScale based on message queue length.

Resource metrics: CPU and memory are built-in resource metrics. Metrics Server provides the information required for these scaling decisions.

Custom metrics: These represent application-specific measurements, such as active connections, request rates, or messages processed per second. They require a compatible custom metrics API adapter.

External metrics: These come from sources outside the Kubernetes workload, such as cloud message queues or external monitoring systems. They require an external metrics adapter.

An HPA can also use multiple metrics simultaneously. Kubernetes calculates a replica recommendation for each metric and selects the highest recommendation, subject to the configured maximum replicas.

Also checkout: What to Learn to Become a DevOps Engineer in 2026?

Kubernetes HPA vs VPA: What Is the Difference?

Kubernetes HPA and VPA are both autoscaling mechanisms, but they solve different resource management problems.

HPA increases or decreases the number of Pods, whereas VPA adjusts the CPU and memory resource requests of existing application containers.

Comparison factorKubernetes HPAKubernetes VPA
Primary purposeAdjusts the number of PodsAdjusts Pod resource requests
Scaling approachHorizontal scalingVertical scaling
Resource adjustmentsChanges replica countChanges CPU and memory requests
Impact on PodsCreates or removes PodsMay restart Pods to apply recommendations
Typical use casesApplications with changing trafficApplications with changing resource requirements

When should you use HPA?

Choose HPA when your application needs additional replicas to handle increasing traffic. It is useful for web applications, APIs, and microservices.

When should you use VPA?

Choose VPA when your application needs more or fewer CPU and memory resources per Pod rather than additional replicas.

You can also use HPA and VPA together, but avoid having both independently control the same CPU or memory resource in ways that conflict with each other.

GUVI Ad

Also read: How Is AI Transforming DevOps? Check 7 Intriguing Ways!

Kubernetes HPA Best Practices

Following the right practices helps make Kubernetes autoscaling more reliable and predictable.

  1. Set appropriate resource requests: Configure CPU and memory requests for containers so HPA can calculate resource utilisation accurately.
  2. Define minimum and maximum replicas: Set suitable replica limits based on application capacity, availability requirements, and infrastructure resources.
  3. Choose realistic scaling targets: Avoid setting CPU or memory targets without understanding your application’s normal resource consumption.
  4. Configure scaling behaviour: Use stabilization windows and scaling policies to prevent unnecessary scaling up and down during short-lived traffic fluctuations.
  5. Monitor application performance: Track CPU, memory, response times, errors, and application-level metrics to understand scaling effectiveness.
  6. Test under realistic workloads: Perform load testing to determine whether your HPA configuration can handle expected traffic patterns.
  7. Plan node capacity: Remember that HPA scales Pods, not worker nodes. If the cluster lacks capacity to schedule new Pods, use a node autoscaling solution such as Cluster Autoscaler alongside HPA.

Common Kubernetes HPA Issues and Troubleshooting

Sometimes HPA may fail to scale applications as expected. Understanding common issues helps identify the problem quickly.

Common issuePossible reasonTroubleshooting command
Unknown metricsMetrics Server is unavailablekubectl top pods
Pods not scaling upMetrics are below target or Pods cannot be scheduledkubectl describe hpa
CPU target not reachedCPU requests are too high or workload is not CPU-intensivekubectl describe deployment
Metrics Server issuesMetrics API or kubelet communication failurekubectl get apiservice v1beta1.metrics.k8s.io
Maximum replicas reachedHPA has reached maxReplicaskubectl get hpa

Here are some additional commands to investigate scaling problems:

Check HPA events:

kubectl describe hpa nginx-hpa

Check resource usage:

kubectl top pods

kubectl top nodes

Check Metrics Server status:

kubectl get pods -n kube-system

Check application events:

kubectl get events –sort-by=.lastTimestamp

Also verify that the target Deployment exists, its Pods have the required resource requests, and the metrics APIs are available.

If the HPA reaches its maximum replica count, review whether the application needs a higher replica limit or whether the underlying infrastructure needs additional capacity.

Conclusion

Kubernetes HPA makes application scaling easier by automatically adjusting Pod replicas based on changing workloads. It helps developers maintain application availability, improve resource utilisation, and reduce the need for manual scaling.

By understanding how Horizontal Pod Autoscaler works, configuring resource requests, choosing suitable scaling targets, and monitoring application metrics, you can build more reliable Kubernetes deployments.

Learning Kubernetes autoscaling is also an important step towards managing production-ready containerised applications. With practical experience in Deployments, Services, HPA, and resource management, you can strengthen your DevOps skills and work more confidently with cloud-native environments.

Frequently Asked Questions (FAQs)

1. What is Kubernetes HPA used for?

Kubernetes HPA is used to automatically increase or decrease the number of Pod replicas based on resource utilisation or configured metrics. It helps applications handle changing workloads efficiently.

2. How does Horizontal Pod Autoscaler work in Kubernetes?

HPA periodically collects application metrics, compares them with configured targets, calculates the required replica count, and updates the target workload’s scale.

3. What metrics does Kubernetes HPA use?

Kubernetes HPA supports CPU utilisation, memory utilisation, custom application metrics, and external metrics. These metrics help determine when an application needs additional or fewer Pods.

4. What is the difference between HPA and VPA in Kubernetes?

HPA changes the number of Pod replicas to handle changing workloads, while VPA adjusts CPU and memory resource requests for individual Pods.

Success Stories

Did you enjoy this article?

Learn with HCL GUVI

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. TL;DR
  2. What Is Kubernetes HPA (Horizontal Pod Autoscaler)?
  3. How Does Horizontal Pod Autoscaler Work in Kubernetes?
  4. Kubernetes HPA Prerequisites
  5. Kubernetes HPA Tutorial: Step-by-Step Implementation
    • Step 1: Create a Kubernetes Deployment
    • Step 2: Expose the Application Using a Service
    • Step 3: Create a Kubernetes HPA
    • Step 4: Check HPA Status
    • Step 5: Generate Traffic to Trigger Scaling
    • Step 6: Configure HPA Using YAML
  6. Kubernetes HPA Metrics and Scaling Targets
  7. Kubernetes HPA vs VPA: What Is the Difference?
  8. Kubernetes HPA Best Practices
  9. Common Kubernetes HPA Issues and Troubleshooting
  10. Conclusion
  11. Frequently Asked Questions (FAQs)
    • What is Kubernetes HPA used for?
    • How does Horizontal Pod Autoscaler work in Kubernetes?
    • What metrics does Kubernetes HPA use?
    • What is the difference between HPA and VPA in Kubernetes?