Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 03 · Networking & ScalingChapter 16 of 33
15.
Phase 03Read time ~15 minDifficulty intermediate

Horizontal Pod Autoscaler (HPA)

Warrior, now we're learning one of the most useful Kubernetes production features:

In this chapter
  • 01What Is HPA?
  • 02Horizontal vs Vertical Scaling
  • 03Horizontal Scaling
  • 04Vertical Scaling
  • 05Why HPA Is Needed
  • 06HPA Architecture
  • 07HPA + Deployment
  • 08HPA Usually Uses Metrics
  • 09Metrics Server
  • 10Check Metrics
  • 11HPA with CPU
  • 12Why Requests Matter for HPA
  • 13Creating an HPA Imperatively
  • 14HPA YAML
  • 15Understanding scaleTargetRef
  • 16minReplicas
  • 17maxReplicas
  • 18CPU Utilization Example
  • 19How Does HPA Calculate Desired Replicas?
  • 20HPA Doesn't Scale Instantly
  • 21HPA + Readiness
  • 22HPA + Resources + Readiness
  • 23Memory-Based HPA
  • 24Multiple Metrics
  • 25Custom Metrics
  • 26External Metrics
  • 27AI Workloads and HPA
  • 28HPA Does Not Create Nodes
  • 29HPA vs Cluster Autoscaler
  • 30HPA
  • 31Cluster Autoscaler
  • 32Example: HPA + Cluster Autoscaler
  • 33HPA Commands
  • 34Understanding kubectl get hpa
  • 35HPA Troubleshooting
  • 36Resource Requests Are Important Again
  • 37Scale Down Carefully
  • 38HPA behavior
  • 39Complete Advanced Example
  • 40Real-World Node.js Example
  • 41HPA + Readiness + Service
  • 42Interview Questions
  • 43Q1. What is HPA?
  • 44Q2. What does horizontal scaling mean?
  • 45Q3. What does HPA scale?
  • 46Q4. What metrics can HPA use?
  • 47Q5. What is Metrics Server?
  • 48Q6. Why are CPU requests important for CPU-based HPA?
  • 49Q7. Does HPA create worker nodes?
  • 50Q8. HPA vs Cluster Autoscaler?
  • 51Q9. Can HPA scale from 2 to 100 Pods?
  • 52Q10. Why shouldn't HPA scale down too aggressively?
  • 53One-line memory trick
  • 54Next → Chapter 16: Cluster Autoscaler
In this chapter (54 sections)
01What Is HPA?02Horizontal vs Vertical Scaling03Horizontal Scaling04Vertical Scaling05Why HPA Is Needed06HPA Architecture07HPA + Deployment08HPA Usually Uses Metrics09Metrics Server10Check Metrics11HPA with CPU12Why Requests Matter for HPA13Creating an HPA Imperatively14HPA YAML15Understanding scaleTargetRef16minReplicas17maxReplicas18CPU Utilization Example19How Does HPA Calculate Desired Replicas?20HPA Doesn't Scale Instantly21HPA + Readiness22HPA + Resources + Readiness23Memory-Based HPA24Multiple Metrics25Custom Metrics26External Metrics27AI Workloads and HPA28HPA Does Not Create Nodes29HPA vs Cluster Autoscaler30HPA31Cluster Autoscaler32Example: HPA + Cluster Autoscaler33HPA Commands34Understanding kubectl get hpa35HPA Troubleshooting36Resource Requests Are Important Again37Scale Down Carefully38HPA behavior39Complete Advanced Example40Real-World Node.js Example41HPA + Readiness + Service42Interview Questions43Q1. What is HPA?44Q2. What does horizontal scaling mean?45Q3. What does HPA scale?46Q4. What metrics can HPA use?47Q5. What is Metrics Server?48Q6. Why are CPU requests important for CPU-based HPA?49Q7. Does HPA create worker nodes?50Q8. HPA vs Cluster Autoscaler?51Q9. Can HPA scale from 2 to 100 Pods?52Q10. Why shouldn't HPA scale down too aggressively?53One-line memory trick54Next → Chapter 16: Cluster Autoscaler

HPA automatically increases or decreases the number of Pods based on workload demand.

Until now, you manually did:

kubectl scale deployment node-api --replicas=5

But real applications have changing traffic:

Morning     → 2 Pods
Afternoon   → 5 Pods
Traffic peak → 10 Pods
Night       → 2 Pods

You don't want someone manually changing replicas every time.

That's what HPA does.


1. What Is HPA?#

HPA stands for:

Horizontal Pod Autoscaler

"Horizontal" means:

More Pods
←───────→

rather than making one Pod bigger.

Example:

Before:
 
Pod 1
Pod 2
 
High traffic:
 
Pod 1
Pod 2
Pod 3
Pod 4
Pod 5

So:

HPA changes the number of Pod replicas.


2. Horizontal vs Vertical Scaling#

This distinction is very important.

Horizontal Scaling#

Add more Pods:

Pod 1
Pod 2
Pod 3
Pod 4

This is HPA's job.


Vertical Scaling#

Give a Pod more resources:

Before:
CPU = 250m
Memory = 256Mi
 
After:
CPU = 1
Memory = 1Gi

That's vertical scaling.

Conceptually:

Horizontal
   ↓
More Pods
 
Vertical
   ↓
Bigger Pods

3. Why HPA Is Needed#

Imagine your Node.js API normally gets:

100 requests/minute

You have:

2 Pods

Suddenly:

10,000 requests/minute

Two Pods may become overloaded.

HPA can detect increased resource utilization and increase replicas:

2 Pods
  ↓
4 Pods
  ↓
8 Pods

When demand decreases:

8 Pods
  ↓
4 Pods
  ↓
2 Pods

4. HPA Architecture#

                   HPA
                    │
                    │ observes metrics
                    ▼
              Metrics API
                    │
                    ▼
               Pod Metrics
                    │
                    ▼
              CPU / Memory
                    │
                    ▼
             Desired Replicas
                    │
                    ▼
               Deployment
                    │
          ┌─────────┼─────────┐
          ▼         ▼         ▼
        Pod 1     Pod 2     Pod 3

HPA doesn't directly create containers itself.

It changes the workload's desired replica count, typically through the target resource such as a Deployment.


5. HPA + Deployment#

Suppose:

spec:
  replicas: 2

HPA may effectively adjust the Deployment toward:

replicas = 5

Then:

Deployment
     ↓
ReplicaSet
     ↓
5 Pods

Remember the hierarchy:

HPA
 ↓
Deployment
 ↓
ReplicaSet
 ↓
Pods

6. HPA Usually Uses Metrics#

HPA needs data.

For example:

CPU utilization
Memory utilization
Custom metrics
External metrics

The simplest example is CPU.

Suppose:

Target CPU = 70%

If Pods consistently exceed that target:

CPU ↑
 ↓
HPA
 ↓
Replicas ↑

If utilization falls:

CPU ↓
 ↓
HPA
 ↓
Replicas ↓

7. Metrics Server#

For basic CPU/memory HPA, Kubernetes commonly uses the Metrics API, often provided by Metrics Server.

You can check:

kubectl top pods

If this doesn't work, Metrics Server may not be installed/configured.

You might see an error similar to:

Metrics API not available

8. Check Metrics#

Run:

kubectl top pods

Example:

NAME                       CPU(cores)   MEMORY(bytes)
node-api-abc               120m         180Mi
node-api-def               150m         190Mi
node-api-ghi               110m         175Mi

And:

kubectl top nodes

shows node-level usage.


9. HPA with CPU#

Suppose your Deployment has:

resources:
  requests:
    cpu: "250m"

and HPA target:

70%

If the container is using:

175m

then:

175 / 250 = 70%

So:

CPU utilization = 70%

This is why Chapter 13 was important.

CPU utilization for HPA is commonly calculated relative to the CPU request.


10. Why Requests Matter for HPA#

Suppose:

requests:
  cpu: "250m"

Actual usage:

200m

Utilization:

200 / 250 = 80%

But if request were:

500m

the same 200m usage would be:

200 / 500 = 40%

Same actual CPU.

Different HPA utilization.

Therefore:

Badly chosen resource requests can lead to misleading autoscaling behavior.


11. Creating an HPA Imperatively#

Suppose:

Deployment:
node-api

You can create an HPA with:

kubectl autoscale deployment node-api \
  --cpu-percent=70 \
  --min=2 \
  --max=10

Meaning:

Minimum Pods = 2
Maximum Pods = 10
Target CPU = 70%

Check:

kubectl get hpa

12. HPA YAML#

In production, declarative YAML is often preferable.

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
 
metadata:
  name: node-api-hpa
 
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: node-api
 
  minReplicas: 2
  maxReplicas: 10
 
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70

Apply:

kubectl apply -f hpa.yaml

Check:

kubectl get hpa

13. Understanding scaleTargetRef#

This:

scaleTargetRef:
  apiVersion: apps/v1
  kind: Deployment
  name: node-api

means:

HPA should control the replica count of node-api.

So:

HPA
 │
 │ controls
 ▼
Deployment/node-api

14. minReplicas#

minReplicas: 2

means:

HPA shouldn't normally scale below 2 replicas.

Even if CPU is very low:

10%
 ↓
HPA
 ↓
2 Pods

not:

0 Pods

15. maxReplicas#

maxReplicas: 10

means:

HPA won't scale this target beyond 10 replicas through this HPA configuration.

So:

Traffic ↑
    ↓
Pods ↑
    ↓
...
10 Pods
    ↓
Maximum reached

If traffic continues increasing, the application may still become overloaded.

That's why autoscaling isn't magic.


16. CPU Utilization Example#

Suppose:

3 Pods

Each has:

CPU request = 250m

Current CPU:

Pod A = 200m
Pod B = 225m
Pod C = 250m

Approximate utilization:

200 / 250 = 80%
225 / 250 = 90%
250 / 250 = 100%

Average:

~90%

Target:

70%

HPA may decide to increase replicas.


17. How Does HPA Calculate Desired Replicas?#

A simplified mental model is:

desired replicas
≈
current replicas ×
(current utilization / target utilization)

Suppose:

Current replicas = 3
Current utilization = 90%
Target = 60%

Then approximately:

3 × (90 / 60)
= 4.5

Kubernetes rounds according to its scaling logic and constraints, so it may move toward:

5 replicas

This is a simplified explanation, not the complete HPA algorithm.


18. HPA Doesn't Scale Instantly#

HPA isn't:

CPU = 71%
 ↓
Instantly add Pod

Kubernetes periodically evaluates metrics and uses stabilization and scaling behavior to avoid excessive oscillation.

So:

Traffic spike
     ↓
Metrics collected
     ↓
HPA evaluates
     ↓
Desired replica count changes
     ↓
Deployment creates Pods
     ↓
Pods start
     ↓
Readiness passes
     ↓
Traffic reaches new Pods

This takes time.


19. HPA + Readiness#

This connects directly to Chapter 14.

Suppose HPA creates:

Pod D

Pod D starts:

Pod D
Starting...

Readiness:

NotReady

Therefore:

Service
 ├── Pod A ✅
 ├── Pod B ✅
 ├── Pod C ✅
 └── Pod D ❌

Once Pod D is ready:

Service
 ├── Pod A ✅
 ├── Pod B ✅
 ├── Pod C ✅
 └── Pod D ✅

That's how HPA and readiness work together.


20. HPA + Resources + Readiness#

These three concepts form a very important production triangle:

             HPA
              │
       scale replicas
              │
              ▼
        Deployment
              │
              ▼
             Pods
              │
       ┌──────┴──────┐
       │             │
   Resources      Readiness
       │             │
       ▼             ▼
 Scheduling      Traffic

Remember this architecture.


21. Memory-Based HPA#

You can also scale based on memory.

Example:

metrics:
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 70

Meaning:

Target average memory utilization = 70%

But memory-based scaling needs careful design.

For example, an application with a steadily growing cache may continually consume memory without traffic increasing.

So:

CPU and memory are signals, not necessarily direct measurements of user traffic.


22. Multiple Metrics#

HPA can use multiple metrics.

For example:

metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
 
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80

Conceptually:

CPU       → 70%
Memory    → 80%
             │
             ▼
             HPA

When multiple metrics are configured, HPA evaluates the desired replica count for each and uses the largest recommended count.


23. Custom Metrics#

CPU and memory aren't always the best scaling signals.

Imagine your API receives:

10,000 requests/second

CPU may still be relatively low.

You might want:

Requests per second

as the scaling signal.

This is where custom metrics can become useful.

Examples:

Requests/second
Queue length
Messages waiting
Active sessions
Application-specific metric

24. External Metrics#

You can also scale based on metrics from outside the cluster.

Examples might include:

Cloud queue depth
External monitoring system
Managed service metric

This requires the appropriate metrics adapter/integration.


25. AI Workloads and HPA#

Since you work with AI systems, imagine an inference API:

POST /generate

Suppose:

Requests ↑
Queue length ↑

CPU might not be the best scaling signal.

Instead:

Queue length > 100
        ↓
Increase inference workers

This is where custom/external metrics become powerful.

A production AI system might use:

Queue depth
GPU utilization
Requests per second
Latency
Tokens/sec

depending on the serving architecture and autoscaling system.


26. HPA Does Not Create Nodes#

This is a critical distinction.

Suppose:

HPA
 ↓
10 Pods

but your cluster doesn't have enough capacity.

You might get:

Some Pods
     ↓
Pending

HPA increased the number of Pods.

It did not create additional worker nodes.

That's the job of:

Cluster Autoscaler or other node autoscaling mechanisms.

We'll learn that in Chapter 16.


27. HPA vs Cluster Autoscaler#

Very important:

HPA#

Scales:

Pods

Cluster Autoscaler#

Scales:

Nodes

Architecture:

Traffic
   │
   ▼
HPA
   │
   ▼
More Pods
   │
   ▼
Not enough node capacity
   │
   ▼
Cluster Autoscaler
   │
   ▼
More Nodes

This is the foundation of elastic Kubernetes clusters.


28. Example: HPA + Cluster Autoscaler#

Suppose:

Cluster
├── Node 1
└── Node 2

Traffic increases.

HPA:

3 Pods
 ↓
8 Pods

But nodes only have capacity for:

5 Pods

So:

5 Pods → Running
3 Pods → Pending

Cluster Autoscaler detects unschedulable Pods:

Pending Pods
    ↓
Cluster Autoscaler
    ↓
Add Node
    ↓
Pending Pods scheduled

Final:

Node 1
Node 2
Node 3
 
8 Pods

29. HPA Commands#

Check HPA:

kubectl get hpa

Detailed:

kubectl describe hpa node-api-hpa

Watch:

kubectl get hpa -w

Check metrics:

kubectl top pods

Check deployment:

kubectl get deployment node-api

Check Pods:

kubectl get pods

30. Understanding kubectl get hpa#

You might see:

NAME           REFERENCE             TARGETS   MINPODS   MAXPODS   REPLICAS
node-api-hpa   Deployment/node-api   75%/70%   2         10        4

Let's decode:

75% / 70%
   ↑     ↑
current target

Meaning:

Current utilization = 75%
Target = 70%

HPA may want to increase replicas.


31. HPA Troubleshooting#

Suppose:

kubectl get hpa

shows:

TARGETS: <unknown>/70%

Possible causes include:

Metrics API unavailable
Metrics Server problem
Missing resource requests
Configuration issues

Check:

kubectl describe hpa node-api-hpa

Also:

kubectl top pods

32. Resource Requests Are Important Again#

Suppose your Deployment:

containers:
  - name: api
    image: my-api

has no CPU request.

Then CPU utilization-based HPA may not work as expected because percentage utilization requires a meaningful CPU request baseline.

So a good pattern is:

resources:
  requests:
    cpu: "250m"
    memory: "256Mi"

before using utilization-based HPA.


33. Scale Down Carefully#

Imagine:

Traffic spike
 ↓
10 Pods

Traffic immediately falls:

Traffic ↓

Should Kubernetes instantly remove 8 Pods?

Probably not.

Rapid scale up/down can cause:

Oscillation
Cold starts
Unnecessary churn
Performance instability

Kubernetes HPA supports scaling behavior controls and stabilization mechanisms.

For example, conceptually:

Scale up:
Fast
 
Scale down:
Slower

This can help prevent aggressive scale-down behavior.


34. HPA behavior#

Modern HPA uses:

behavior:

Example:

behavior:
  scaleDown:
    stabilizationWindowSeconds: 300

Meaning:

Avoid immediately scaling down based on transient metric changes; use a stabilization window.

You can also control scale-up/down policies.


35. Complete Advanced Example#

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
 
metadata:
  name: node-api-hpa
 
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: node-api
 
  minReplicas: 2
  maxReplicas: 10
 
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 0
 
    scaleDown:
      stabilizationWindowSeconds: 300
 
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70

This says:

Minimum = 2
Maximum = 10
CPU target = 70%
 
Scale up:
quickly
 
Scale down:
stabilize for ~5 minutes

Exact behavior depends on the complete HPA configuration and controller evaluation.


36. Real-World Node.js Example#

Imagine:

Node.js API

Deployment:

resources:
  requests:
    cpu: "250m"
    memory: "256Mi"
 
  limits:
    cpu: "1"
    memory: "512Mi"

HPA:

minReplicas: 2
maxReplicas: 10

Target:

CPU = 70%

Traffic:

Low
 ↓
2 Pods
 
Medium
 ↓
4 Pods
 
High
 ↓
7 Pods
 
Very high
 ↓
10 Pods

If cluster capacity is insufficient:

HPA
 ↓
More Pods
 ↓
Pending Pods
 ↓
Cluster Autoscaler
 ↓
More Nodes

37. HPA + Readiness + Service#

This is the complete production flow:

                     TRAFFIC
                        │
                        ▼
                     Service
                        │
            ┌───────────┼───────────┐
            ▼           ▼           ▼
          Pod A       Pod B       Pod C
           ✅           ✅           ❌
          Ready       Ready       NotReady
            │           │
            └──────┬────┘
                   │
                 Traffic
 
                    ▲
                    │
                   HPA
                    │
             CPU / Memory
                    │
                    ▼
             More / fewer Pods

This is a very important Kubernetes pattern.


38. Interview Questions#

Q1. What is HPA?#

Horizontal Pod Autoscaler automatically adjusts the number of Pod replicas of a scalable workload based on observed metrics.


Q2. What does horizontal scaling mean?#

More Pods

rather than:

Bigger Pod

Q3. What does HPA scale?#

Usually a scalable workload such as a Deployment by adjusting its desired replica count.


Q4. What metrics can HPA use?#

Examples:

CPU
Memory
Custom metrics
External metrics

Q5. What is Metrics Server?#

A component commonly used to provide basic resource usage metrics through the Kubernetes Metrics API.


Q6. Why are CPU requests important for CPU-based HPA?#

Because CPU utilization targets are commonly calculated relative to CPU requests.


Q7. Does HPA create worker nodes?#

No.

HPA scales Pods.

Cluster/node autoscaling handles node capacity.


Q8. HPA vs Cluster Autoscaler?#

HPA
 ↓
Pods
 
Cluster Autoscaler
 ↓
Nodes

Q9. Can HPA scale from 2 to 100 Pods?#

Technically, if configured with:

maxReplicas: 100

yes, but actual cluster capacity and application behavior determine whether those Pods can run successfully.


Q10. Why shouldn't HPA scale down too aggressively?#

To avoid oscillation, cold starts, unnecessary Pod churn, and unstable capacity.


🧠 Chapter 15 Cheat Sheet#

HPA
 │
 ├── minReplicas
 ├── maxReplicas
 ├── metrics
 └── target
       │
       ▼
Deployment
       │
       ▼
Pods

CPU-based scaling:

CPU utilization ↑
       ↓
HPA
       ↓
Replicas ↑

When demand falls:

CPU utilization ↓
       ↓
HPA
       ↓
Replicas ↓

But:

HPA → Pods
Cluster Autoscaler → Nodes

🎯 The Scaling Architecture#

You now have the full picture:

                         INTERNET
                            │
                            ▼
                         Ingress
                            │
                            ▼
                         Service
                            │
              ┌─────────────┼─────────────┐
              ▼             ▼             ▼
            Pod 1         Pod 2         Pod 3
              │             │             │
              └─────────────┼─────────────┘
                            ▲
                            │
                           HPA
                            ▲
                            │
                    CPU / Memory / Metrics
                            │
                            ▼
                    Replica adjustment
                            │
                            ▼
                     More / fewer Pods
                            │
                     Capacity problem?
                            │
                            ▼
                  Cluster Autoscaler
                            │
                            ▼
                       More Nodes

One-line memory trick#

HPA scales Pods; Cluster Autoscaler scales Nodes.


Next → Chapter 16: Cluster Autoscaler#

We'll go one level deeper:

Pod Pending
     ↓
Insufficient node capacity
     ↓
Cluster Autoscaler
     ↓
New worker node
     ↓
Scheduler
     ↓
Pod gets placed

We'll cover node pools, scale-up, scale-down, cloud Kubernetes behavior, EKS/GKE/AKS concepts, and how HPA + Cluster Autoscaler work together.

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 14 — Health Checks & ProbesNext ChapterChapter 16 — Cluster Autoscaler
PrevNext