Scaling and Autoscaling

Scale order service Pods manually, understand CPU-based HPA autoscaling, and configure and verify it in a kind cluster.

🎯 Introduction

Suppose the order service has two Pods. They handle normal traffic, but a promotional event suddenly brings more orders and both become busy. Adding Pods lets more instances share the requests.

But must someone decide how many Pods to add or remove every time traffic changes? Frequent manual adjustments are cumbersome and may come too late.

This article starts with manual scaling, then introduces HPA autoscaling: how it determines the required Pod count and where it gets its metrics.


🧱 Adding an order service Pod

Our Deployment already runs two orders Pods. Increase the replica count from two to three:

kubectl scale deployment/orders --replicas=3 -n course

Simulated output:

deployment.apps/orders scaled

This changes the Deployment's desired Pod count to three. Check the result:

kubectl get deployment orders -n course
kubectl get pods -n course -l app=orders

Simulated output; Pod names will differ:

NAME     READY   UP-TO-DATE   AVAILABLE   AGE
orders   3/3     3            3           35m

NAME                         READY   STATUS    RESTARTS   AGE
orders-7c8d9f6b5-a1b2c      1/1     Running   0          35m
orders-7c8d9f6b5-d3e4f      1/1     Running   0          35m
orders-7c8d9f6b5-f5g6h      1/1     Running   0          20s

The original two Pods remain running, and a new Pod appears. Once it is ready, the Service can also forward eligible requests to it.

Manual scaling changes the replica count in the cluster, not your local deployment.yaml. Reapplying YAML with the old count may change it back.

Three Pods do not guarantee exactly 50% more capacity. If the database is already overloaded, adding order Pods cannot resolve that bottleneck.

Restore two replicas so the autoscaling example starts from the original count:

kubectl scale deployment/orders --replicas=2 -n course

📈 Why use HPA?

We just told Kubernetes to run three order Pods. If traffic rises today and falls tomorrow, we would need to keep adjusting the count ourselves.

The HorizontalPodAutoscaler (HPA) automatically adjusts Deployment replicas based on resource usage. It may add Pods when busy and remove them when idle. It changes the number of Pods, rather than directly adding CPU to an individual Pod.

How does HPA determine CPU utilization?

Recall the order container's configuration from Resource Requests and Limits:

resources:
  requests:
    cpu: 100m

100m declares a requirement of 0.1 CPU cores. With a target CPU utilization of 60%, interpret usage as follows:

Actual CPU used by one order PodRelative to the 100m requestCompared with the 60% target
30m30%Low; scaling down may be considered
60m60%Near the target
90m90%High; scaling up may be considered

For example, if two Pods each use 90m, their average utilization is 90%, above the 60% target. If this persists, HPA may increase the count from two to around three to share the work.

The 60% is relative to Pod CPU requests, not the CPU utilization of your entire computer. HPA considers average metrics across Pods and scaling rules; it does not immediately add a Pod whenever utilization crosses 60%. It also respects replica bounds. With minReplicas: 2, as configured below, low utilization cannot reduce two Pods to one.

Where does HPA get CPU usage metrics?

A component called Metrics Server collects Pod CPU and memory usage metrics from cluster nodes and exposes them to HPA through the Kubernetes resource metrics API.

How does the HPA scale order Pods?

The HPA gets actual CPU usage, compares it with the target, and adjusts the Deployment replica count.

① Running application

Order Pod

orders-1orders-2

Runs Node.js and consumes CPU

② Collect resource metrics

Metrics Server

CPU: 90m / Pod

Collects metrics from nodes and makes them available to Kubernetes

③ Decide whether to scale

HPA

Current: 90% / Target: 60%

Sustained usage above the target may call for more replicas

④ Run with the new replica target

Deployment

2 → 3 Pods

Creates order Pods to share the request load

Each Pod requests 100m CPU and uses 90m in this example. Scaling takes time and depends on metrics, replica limits, and scaling rules.

Think of the flow as: Pods consume CPU → Metrics Server supplies metrics → HPA compares them with the target → the Deployment adjusts the Pod count.


🛠 Configuring HPA in kind

1. Confirm CPU metrics are available

Continue using the node-course kind cluster. First, confirm your current context:

kubectl config current-context

It should be kind-node-course. If not, run kubectl config use-context kind-node-course before continuing.

Next, check that the CPU requests configured in Resource Requests and Limits are still present:

kubectl describe deployment orders -n course

Under Containers → orders → Requests, look for cpu: 100m, retaining other resource settings. Without CPU requests, HPA cannot calculate utilization as the percentage used here.

A kind cluster usually requires you to install Metrics Server yourself. Run kubectl version, check Server Version, and choose a release using the official compatibility matrix.

For example, on Kubernetes 1.34 or later:

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
kubectl rollout status deployment/metrics-server -n kube-system --timeout=120s

For server versions 1.31–1.33, replace the installation URL with https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.8.1/components.yaml. For other versions, follow the compatibility matrix. This installs the cluster metrics component, not the order service.

Verify that metrics are readable:

kubectl top pods -n course

Simulated output; actual CPU and memory usage will differ:

NAME                         CPU(cores)   MEMORY(bytes)
orders-7c8d9f6b5-a1b2c      8m           38Mi
orders-7c8d9f6b5-d3e4f      12m          40Mi

CPU and memory values confirm that resource metrics are available. Collection may take a short time after installation, so temporarily missing metrics do not necessarily indicate failure.

If metrics are unavailable: inspect Metrics Server logs first:

kubectl logs -n kube-system deployment/metrics-server --tail=30

If the logs show an x509 certificate validation error, confirm that the current cluster is kind-node-course, then use the following only in this local practice environment:

kubectl -n kube-system patch deployment metrics-server \
  --type=json \
  -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'

kubectl rollout status deployment/metrics-server -n kube-system --timeout=120s
kubectl top pods -n course

--kubelet-insecure-tls skips kubelet certificate validation. Use it only for local troubleshooting, not directly in production. If metrics remain unavailable, inspect Metrics Server status and logs.

2. Create the HPA configuration

Once metrics are readable, create hpa.yaml in your course directory:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: orders
  namespace: course
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: orders
  minReplicas: 2
  maxReplicas: 5
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 60

Focus on four settings:

SettingMeaning
scaleTargetRefHPA adjusts the orders Deployment
minReplicas: 2Normally retains at least two Pods during autoscaling
maxReplicas: 5Scales to at most five Pods
averageUtilization: 60Targets average CPU utilization near 60% of requests

Run:

kubectl apply -f hpa.yaml

Simulated output:

horizontalpodautoscaler.autoscaling/orders created

🔎 How can you check that HPA works?

Inspect HPA status:

kubectl get hpa -n course

Simulated output for an idle cluster; values are illustrative:

NAME     REFERENCE           TARGETS   MINPODS   MAXPODS   REPLICAS   AGE
orders   Deployment/orders   25%/60%   2         5         2          2m

The order service's current average CPU utilization is about 25%, the target is 60%, the allowed range is two to five replicas, and it currently has two replicas.

Inspect more detailed metrics and events with:

kubectl describe hpa orders -n course

If you see <unknown>/60%, metrics are not being obtained correctly yet. First check whether kubectl top pods -n course returns data and whether the order container has CPU requests configured.

Why has it not scaled up? The local service has little sustained traffic, so CPU utilization may remain below target. Creating HPA does not automatically add Pods: it evaluates actual metrics. Observing real scale-up requires sustained load; we will not introduce extra load-testing tools here.

Two other points matter: HPA continuously manages the Deployment's replica count and may override manual kubectl scale changes. Also, adding Pods does not automatically resolve database or other downstream bottlenecks.

To avoid interfering with manual replica management in later articles, complete the exercise below, then delete the practice HPA and restore two replicas:

kubectl delete hpa orders -n course
kubectl scale deployment/orders --replicas=2 -n course

Deleting HPA does not automatically restore two replicas, so scale is a separate step.


❓ Questions and answers

Q: Does HPA scale up immediately at 60% CPU utilization?

No. It periodically reads metrics and considers average utilization, scaling bounds, and other rules. Brief changes do not necessarily trigger scaling.

Q: Can this HPA scale MySQL directly?

No. Our HPA manages only the Pod count of the orders Deployment. Analyze database bottlenecks separately.

Q: Should manual scaling and HPA continuously manage the same Deployment?

It is not recommended. With HPA enabled, automatic adjustments may override manual replica changes.


🧪 Exercise

Suppose the order service has two Pods, each requesting 100m CPU. HPA targets 60% CPU utilization, with a minimum of two replicas and a maximum of five. Answer:

  1. If both Pods continuously use 90m CPU, might HPA add or remove Pods? Why?
  2. If both use only 20m, will HPA reduce the replica count to one? Why?

Success criteria: Explain that 90m is 90% of a 100m request, why HPA might scale up, and why it cannot go below the minimum replica count. Clean up HPA afterward using the earlier commands.


🎉 You can now add order Pods manually, explain how HPA adjusts replicas from CPU usage, and inspect autoscaling status in a local cluster.