Containers and Kubernetes · Advanced · 22 min
Scale Snip automatically with a HorizontalPodAutoscaler
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Kubernetes 1.37 · kind 0.33 · metrics-server 0.9.1 · Kustomize 5.8.3
You will run Snip on a three-node kind cluster where a HorizontalPodAutoscaler adds and removes pods by CPU load, a PodDisruptionBudget keeps two pods serving while a node is drained, and the pods spread across the workers.
On this page
So far Snip runs a fixed number of pods. That number is a guess: too few and a busy hour slows every request, too many and you pay for idle CPU all night. A HorizontalPodAutoscaler (HPA) replaces the guess with a rule, such as "keep average CPU near 60% of what each pod asked for", and changes the Deployment's replica count to follow it.
Autoscaling only helps if the extra pods survive the cluster's own maintenance, so this part also covers the other half: a PodDisruptionBudget that stops a node drain from taking Snip below two serving pods, and a spread rule that keeps those pods on different nodes. To have more than one node to spread across, the kind cluster gains two workers.
This is part 6 of 8 in Ship a Go API to Kubernetes. Everything you add lives in ~/snip-demo/k8s, next to the base and overlays from part 2. The commands assume the names used so far: the kind cluster snip, the namespace snip, the Deployment and Service snip, and pods labelled app.kubernetes.io/name: snip. If you chose different names, use yours.
Step 1 · Give the kind cluster two worker nodes
A kind cluster's node list is fixed when the cluster is created. There is no command to add a node to a running cluster, so you change the config file and create the cluster again. The cost is that everything inside it goes: the Gateway API controllers from part 5, the PostgreSQL volume from part 3 and the links you created. On a laptop cluster that is acceptable; it is also good practice in rebuilding from files.
Write the new config. The control-plane entry keeps the port mappings from part 5 (shown here as host ports 80 and 443 mapped to node ports 30080 and 30443; keep your own values if they differ). The two worker entries are the change:
mkdir -p ~/snip-demo/kind
cat > ~/snip-demo/kind/cluster.yaml <<'YAML'
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
image: kindest/node:v1.37.0
extraPortMappings:
- containerPort: 30080
hostPort: 80
listenAddress: "127.0.0.1"
protocol: TCP
- containerPort: 30443
hostPort: 443
listenAddress: "127.0.0.1"
protocol: TCP
- role: worker
image: kindest/node:v1.37.0
- role: worker
image: kindest/node:v1.37.0
YAML
grep -c 'role: worker' ~/snip-demo/kind/cluster.yaml
grep -c 'listenAddress: "127.0.0.1"' ~/snip-demo/kind/cluster.yamlThe first grep prints 2 workers and the second 2 mappings that still listen only on 127.0.0.1, so nobody else on your network can reach the demo. Port mappings stay on the control-plane node: a NodePort Service answers on every node, so the gateway is still reachable even when its proxy pod runs on a worker.
The next commands delete the cluster and every object in it. Make sure nothing in it matters to you before you run them:
kind delete cluster --name snip
kind create cluster --name snip --config ~/snip-demo/kind/cluster.yaml --wait 180s
kind load docker-image snip:0.1.0 --name snipReplace snip:0.1.0 with the image tag you built in part 1. kind load copies the image to all three nodes, which matters now: a pod scheduled on a worker can only start from an image that worker holds. Then repeat the install steps from part 5 (the Gateway API CRDs, Envoy Gateway and cert-manager) and apply ~/snip-demo/k8s/platform again, so the Gateway exists before the dev overlay's routes. The snip-db Secret from part 3 was created by hand, not from the manifests, so it went with the old cluster. Without it PostgreSQL, the migration Job and Snip all fail to start. Create the namespace, recreate the Secret from the same files as in part 3, apply the dev overlay and run the schema migration Job again:
cd ~/snip-demo
kubectl create namespace snip
kubectl create secret generic snip-db -n snip \
--from-file=password=.secrets/password \
--from-file=database-url=.secrets/database-url
kubectl apply -k ~/snip-demo/k8s/overlays/dev
kustomize build ~/snip-demo/k8s/migrate | kubectl apply -n snip -f -
kubectl wait job/snip-migrate -n snip --for=condition=Complete --timeout=180s
kubectl rollout status deployment/snip -n snip --timeout=180sCheck it worked
kubectl get nodesYou see three nodes, snip-control-plane, snip-worker and snip-worker2, all Ready and on v1.37.0. kubectl get pods -n snip -o wide shows the Snip and PostgreSQL pods running on the workers: kind's control-plane node has a NoSchedule taint, so ordinary pods avoid it.
Step 2 · Install metrics-server
An HPA cannot measure anything by itself. It reads CPU and memory figures from the resource metrics API (metrics.k8s.io), and in most clusters metrics-server provides that API by polling each node's kubelet. kind does not install it, so you add it.
On kind there is one snag. Each kubelet serves its stats over HTTPS with a self-signed certificate that the cluster's CA did not sign, so metrics-server refuses to connect. The flag --kubelet-insecure-tls tells it to skip that check. That is fine on a cluster that lives on your laptop and never acceptable on a shared or production cluster, where the fix is kubelet serving certificates signed by the cluster CA. Keeping the flag in its own folder, applied only to kind, makes the exception obvious to the next person.
Download the release manifest and pin it in a folder of its own:
mkdir -p ~/snip-demo/k8s/metrics-server
cd ~/snip-demo/k8s/metrics-server
curl -fsSLo components.yaml https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.9.1/components.yaml
cat > kustomization.yaml <<'YAML'
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- components.yaml
patches:
# Local kind clusters only: kubelet certificates there are self-signed.
- target:
kind: Deployment
name: metrics-server
namespace: kube-system
patch: |-
- op: add
path: /spec/template/spec/containers/0/args/-
value: --kubelet-insecure-tls
YAML
kustomize build . | kubeconform -strict -summary -kubernetes-version 1.37.3
kustomize build . | grep -- '--kubelet-insecure-tls'The JSON patch appends one argument to the end of the container's existing list, so you never edit the downloaded file by hand. kubeconform reports something like Summary: 9 resources found parsing stdin - Valid: 9, Invalid: 0, Errors: 0, Skipped: 0 for the release's nine objects, and the grep prints the added flag. Apply it and wait for the pod:
kubectl apply -k ~/snip-demo/k8s/metrics-server
kubectl rollout status deployment/metrics-server -n kube-system --timeout=120sCheck it worked
metrics-server needs about a minute to collect its first samples. Then:
kubectl top nodes
kubectl top pods -n snipBoth commands print CPU in millicores and memory in MiB for each node and each pod. An idle Snip pod uses only a few millicores. If you see error: Metrics API not available, wait another minute; if it persists, kubectl logs -n kube-system deployment/metrics-server usually shows an x509 error, which means the flag did not reach the pod.
Step 3 · Add a HorizontalPodAutoscaler on CPU
CPU utilisation in an HPA is not a share of the node. It is a share of the CPU the pod requested. A pod that requests 100m and uses 80m is at 80%. Without a request there is nothing to divide by, the HPA reports <unknown> and never scales. Part 2 gave Snip's container requests; check they reach the rendered Deployment:
cd ~/snip-demo/k8s
kustomize build overlays/dev | grep -A3 'requests:'You see cpu: and memory: under requests:. If the command prints nothing, add requests first, as in /tutorials/set-cpu-and-memory-requests-and-limits.
The controller checks every 15 seconds and works out the replica count from one ratio:
desired replicas = ceil(current replicas × current utilisation ÷ target utilisation)
Three pods averaging 90% against a 60% target gives ceil(3 × 90 ÷ 60) = 5. Within 10% of the target it does nothing, which stops it chasing noise.
Write the HPA into the base, so both environments get it:
cd ~/snip-demo/k8s/base
cat > hpa.yaml <<'YAML'
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: snip
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: snip
minReplicas: 3
maxReplicas: 6
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Pods
value: 2
periodSeconds: 30
scaleDown:
stabilizationWindowSeconds: 120
policies:
- type: Pods
value: 1
periodSeconds: 60
YAML
kustomize edit add resource hpa.yaml
grep -A5 '^resources:' kustomization.yamlkustomize edit add resource appends the file to the base's resource list for you. What the fields mean:
minReplicas: 3is the floor. It is three, not two, because of the disruption budget later in this part: to drain a node while keeping two pods serving, there must be a third to lose.maxReplicas: 6is the ceiling, and your cost limit. Size it to what the cluster, and PostgreSQL's connection limit, can take.behavior.scaleUpadds at most two pods every 30 seconds, with no waiting window, so Snip reacts to a spike quickly.behavior.scaleDownis where most clusters need tuning. Without abehaviorblock, Kubernetes waits 300 seconds before scaling down and may then remove many pods at once. Here the HPA looks back over 120 seconds and picks the highest recommendation in that window, so a short dip in traffic does not remove pods that the next burst needs, and it then removes one pod per minute. Kubernetes 1.37 also accepts a per-directiontolerancefield if the default 10% is too coarse for you.
Production traffic is larger, so give prod a higher floor and ceiling with a patch in its overlay:
cd ~/snip-demo/k8s/overlays/prod
cat > hpa-patch.yaml <<'YAML'
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: snip
spec:
minReplicas: 4
maxReplicas: 12
YAML
kustomize edit add patch --path hpa-patch.yamlCheck it worked
Render both overlays and validate them against the 1.37 schemas:
cd ~/snip-demo/k8s
kustomize build overlays/dev | kubeconform -strict -summary -kubernetes-version 1.37.3
kustomize build overlays/dev | grep -E 'minReplicas|maxReplicas'
kustomize build overlays/prod | grep -E 'minReplicas|maxReplicas'kubeconform reports no invalid resources. dev shows maxReplicas: 6 and minReplicas: 3; prod shows maxReplicas: 12 and minReplicas: 4.
Step 4 · Hand the replica count to the autoscaler
The overlays still set a replica count from part 2, and that now fights the HPA. Every kubectl apply would reset the Deployment to that number, the HPA would scale it back, and pods would start and stop for no reason. The count has to leave the manifests, but in the right order: if you delete it from the files first, the next kubectl apply sees a field that was removed and drops it from the Deployment, which falls back to the default of one replica until the HPA catches up.
Apply the HPA while the replica count is still in place:
kubectl apply -k ~/snip-demo/k8s/overlays/dev
kubectl get hpa snip -n snipThen remove spec.replicas from the record kubectl keeps of your last apply. This opens the record in your editor:
kubectl apply edit-last-applied deployment/snip -n snipDelete the replicas: line under spec:, save and close. No pods change at this step; kubectl only forgets that it ever managed the field.
Now take the count out of the files. Open ~/snip-demo/k8s/overlays/dev/kustomization.yaml and ~/snip-demo/k8s/overlays/prod/kustomization.yaml and delete the replicas: block in each (the - name: snip and count: lines under it go too). If base/deployment.yaml has a replicas: line under spec:, delete that as well.
Apply again. This time nothing should change:
kubectl apply -k ~/snip-demo/k8s/overlays/devCheck it worked
The only replica fields left in the rendered output belong to the HPA:
cd ~/snip-demo/k8s
kustomize build overlays/dev | grep -n 'eplicas'
kustomize build overlays/prod | grep -n 'eplicas'
for env in dev prod; do
if kustomize build overlays/$env | grep -qE '^\s+replicas:'; then
echo "$env still sets replicas"; false
fi
done
echo "no bare replicas field"The first two commands print just the maxReplicas and minReplicas lines. The loop prints dev still sets replicas (or prod) and fails if a bare replicas: line is left in the rendered Deployment; when both are clean you see no bare replicas field. On the cluster, kubectl get deployment snip -n snip shows 3/3 ready, the HPA's floor.
Step 5 · Put Snip under load and watch it scale
Generate load from inside the cluster, so your laptop's network is not part of the measurement. The pod below runs eight shell loops, each fetching Snip's health endpoint through the Service as fast as it can:
kubectl run load -n snip --image=busybox:1.37 --restart=Never -- \
/bin/sh -c 'for i in 1 2 3 4 5 6 7 8; do (while true; do wget -q -O /dev/null http://snip/healthz; done) & done; wait'The Service from part 2 listens on port 80, so http://snip/ reaches it by its short DNS name inside the snip namespace. In a second terminal, watch the autoscaler:
kubectl get hpa snip -n snip --watchWithin a minute the TARGETS column climbs above the target, to something like cpu: 145%/60%, and REPLICAS rises by two at a time until utilisation settles near 60% or the count reaches 6. If utilisation stays below 60% on a fast machine, start a second load pod (load2) with the same command.
kubectl describe hpa snip -n snip explains each decision in its events, for example a line like New size: 5; reason: cpu resource utilization (percentage of request) above target. kubectl top pods -n snip shows the load spreading over the new pods.
Stop the load:
kubectl delete pod load -n snipCheck it worked
Keep the watch running. Utilisation drops at once, but REPLICAS holds for about two minutes (the stabilisation window), then falls by one pod a minute until it is back at 3. If replicas never moved at all, kubectl describe hpa snip -n snip shows why: <unknown> utilisation points at metrics-server or a missing request.
On a cloud cluster each new pod may also need a new node, which a cluster autoscaler adds and bills for. maxReplicas is the line that keeps a traffic spike, or a bug in a load test, from turning into a large bill. That matters most where you pay per hour or in prepaid credit.
Step 6 · Spread Snip's pods across the workers
Three pods on one node give you three copies and one point of failure. A topology spread constraint asks the scheduler to keep pod counts per node level. Add it to the base Deployment as a patch:
cd ~/snip-demo/k8s/base
cat > spread-patch.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
name: snip
spec:
template:
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
nodeTaintsPolicy: Honor
labelSelector:
matchLabels:
app.kubernetes.io/name: snip
matchLabelKeys:
- pod-template-hash
YAML
kustomize edit add patch --path spread-patch.yamlRead the fields as one sentence: across nodes (kubernetes.io/hostname), keep the difference between the busiest and the emptiest node to one Snip pod (maxSkew: 1).
whenUnsatisfiable: ScheduleAnywaymakes the rule a strong preference, not a law. WithDoNotSchedule, a pod that cannot be placed evenly staysPending, which is the wrong outcome in the middle of a drain or a scale-up.nodeTaintsPolicy: Honorleaves out nodes the pod cannot run on. Without it, the tainted control-plane node counts as a node with zero Snip pods and skews every calculation.matchLabelKeys: [pod-template-hash]counts only pods of the current ReplicaSet, so during a rollout the old pods that are about to go do not distort where the new ones land.
Check it worked
cd ~/snip-demo/k8s
kustomize build overlays/dev | kubeconform -strict -summary -kubernetes-version 1.37.3
kustomize build overlays/dev | grep -A3 'topologySpreadConstraints:'kubeconform reports no invalid resources and the constraint appears in the rendered Deployment. Apply it with kubectl apply -k ~/snip-demo/k8s/overlays/dev. The change to the pod template starts a rollout; afterwards kubectl get pods -n snip -l app.kubernetes.io/name=snip -o wide shows the three pods split two and one across snip-worker and snip-worker2.
Step 7 · Keep two pods serving through a node drain
Draining a node is how you take it out for maintenance: kubectl drain marks it unschedulable, then evicts its pods through the Eviction API, which checks PodDisruptionBudgets, so a budget can refuse an eviction until the app is safe. Write Snip's budget:
cd ~/snip-demo/k8s/base
cat > pdb.yaml <<'YAML'
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: snip
spec:
minAvailable: 2
unhealthyPodEvictionPolicy: AlwaysAllow
selector:
matchLabels:
app.kubernetes.io/name: snip
YAML
kustomize edit add resource pdb.yamlminAvailable: 2 means an eviction is allowed only while at least two other Snip pods stay ready. This is why the HPA's floor is three: with exactly two pods and minAvailable: 2, no eviction is ever allowed and a drain waits forever. unhealthyPodEvictionPolicy: AlwaysAllow lets a drain remove pods that are already failing their readiness probe, so a broken pod cannot hold a node hostage. The budget only guards voluntary evictions; a node that crashes takes its pods with it, which is what the spread rule is for.
Validate and apply:
cd ~/snip-demo/k8s
kustomize build overlays/dev | kubeconform -strict -summary -kubernetes-version 1.37.3
kustomize build overlays/prod | kubeconform -strict -summary -kubernetes-version 1.37.3
kustomize build overlays/dev | grep -B2 -A6 'kind: PodDisruptionBudget'kubectl apply -k ~/snip-demo/k8s/overlays/dev
kubectl get pdb snip -n snipkubectl get pdb shows MIN AVAILABLE 2 and ALLOWED DISRUPTIONS 1 with three ready pods.
Before you drain, find where PostgreSQL runs. Its volume from part 3 comes from kind's local-path provisioner, which stores data on one node's disk, so the PostgreSQL pod can only ever run on that node. Drain the other worker, or Snip loses its database and every readiness probe fails:
kubectl get pods -n snip -o wideNote the NODE of the PostgreSQL pod. The commands below assume it is on snip-worker2, so they drain snip-worker; swap the names if yours is the other way round. Keep a watch on Snip's pods in a second terminal (kubectl get pods -n snip -l app.kubernetes.io/name=snip -o wide --watch), then drain:
kubectl drain snip-worker --ignore-daemonsets --delete-emptydir-data --timeout=180s--ignore-daemonsets is needed because every node runs DaemonSet pods (kind's network and kube-proxy) that drain cannot move. When two Snip pods sit on that worker, drain evicts one and is refused for the second with a message like Cannot evict pod as it would violate the pod's disruption budget. It retries every few seconds; once the replacement is ready on snip-worker2, the second eviction succeeds.
Check it worked
While the drain runs, the watch never shows fewer than two Snip pods 1/1 ready. When it finishes, kubectl get nodes lists snip-worker as Ready,SchedulingDisabled and all three Snip pods run on snip-worker2. Put the node back:
kubectl uncordon snip-workerKubernetes does not move running pods back after an uncordon; the spread evens out again as pods are replaced, at the next rollout or scale-up. Leave the cluster running for part 7.
Next steps
- Part 7 locks the
snipnamespace down with Pod Security and network policies: /tutorials/lock-down-the-snip-namespace-with-network-policies. Your load pod would be blocked there, so it is worth running the scaling test before you start. - Pick requests that make the HPA's percentages mean something: /tutorials/set-cpu-and-memory-requests-and-limits.
- Readiness decides when a new pod counts towards the budget; revisit the probes from part 4: /tutorials/keep-snip-healthy-with-probes-and-graceful-shutdown.
- Go beyond spreading with node affinity, taints and tolerations: /tutorials/control-where-pods-run-with-affinity-and-taints.
Related tutorials
- Validate Kubernetes manifests before they reach a clusterYou will have one script that checks plain, Kustomize, Helm, generated and custom-resource manifests against the Kubernetes 1.37 schemas and a set of lint rules, with no cluster, and a GitHub Actions job that runs it on every pull request.
- Use secrets in Docker builds without leaking them into the imageYou will find a token and a private key leaking through a Docker build with Trivy 0.76, then fix the build with secret and SSH mounts, carry the fix into Compose and GitHub Actions, and prove with a rescan that the build context is clean.
- Store data in Kubernetes with persistent volumes and claimsYou will claim storage on a Kubernetes 1.37 kind cluster, prove the data outlives its pod, see which access modes and reclaim policies keep or lose data, and know how expansion and snapshots work on a cloud CSI driver.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials