Reduce Kubernetes infrastructure costs with proper resource requests, cluster autoscaling, spot node pools, and namespace quotas.
Orientation Kubernetes cost control lives at the intersection of scheduler decisions, autoscaling logic, and underlying infrastructure pricing. When pod requests diverge from actual usage, when autoscaler metrics are missing, or when spot‑instance eviction outpaces pod graceful‑shutdown handling, cloud bills climb faster than engineering velocity. This page maps the concrete knobs and commands you can turn to keep resource consumption proportional to workload demand, across any cloud that runs Kubernetes.
The Kubernetes scheduler bases placement on *requests*; the runtime enforces *limits*. Confusing the two is the single most common source of both over‑provisioning and silent OOM kills.
CPU and memory syntax In a Pod or Deployment spec, the resources block per container uses two fields:
containers:
- name: api
resources:
requests:
cpu: "200m"
memory: "256Mi"
limits:
cpu: "500m"
memory: "512Mi"
requests are the minimum the scheduler guarantees and the default metric the HPA uses. limits are the hard ceiling the container cannot exceed; exceeding them triggers the kernel OOM killer (not the OOM balancer). The scheduler only places a pod when remaining node capacity (capacity minus aggregate requests of existing pods) meets or exceeds the pod’s request sum. Limits are ignored by the scheduler but strictly enforced by the container runtime.
Applying limits via kubectl To adjust a single Deployment without opening a YAML editor:
kubectl set resources deployment/api \
--requests-cpu=200m --requests-memory=256Mi \
--limits-cpu=500m --limits-memory=512Mi
To inspect current values:
kubectl get deployment api -o jsonpath='{.spec.template.spec.containers[0].resources}'
Scheduler behaviour If a node has 4 CPU and already hosts pods with 3 CPU of requests, a new pod requesting 2 CPU won’t fit. Raising requests without raising limits can improve packing but risks OOM; lowering requests without adjusting limits can cause the HPA to scale too aggressively.
Autoscaling operates at two levels: per‑pod (VPA/HPA) and per‑node (Cluster Autoscaler). Each has distinct triggers, configuration keys, and failure modes.
The HPA watches metrics from the metrics‑server and adjusts replica count. The autoscaling/v1 API is the default; autoscaling/v2 adds custom‑metric support and a behavior field for more granular scaling policies.
To create an HPA that scales on CPU:
kubectl autoscale deployment/api \
--min=2 --max=10 \
--cpu-percent=70
This flag sets targetCPUUtilizationPercentage inside the HorizontalPodAutoscaler spec. The controller divides the current CPU request into the measured usage percent.
For custom metrics (e.g., request queue depth), use autoscaling/v2 and specify metrics[].resource.name. The HPA then references a Prometheus, OpenTelemetry, or other adapter series—not a built‑in field.
Common pitfall: If the metrics‑server is down or misconfigured, kubectl get hpa shows DESIRED but CURRENT stays put. Autoscaling silently stalls because no usage data is reported.
VPA learns request/limit recommendations and can auto‑apply them. It runs as a deployment and watches container metrics. Three modes control behaviour:
| Mode | Action |
|---|---|
off | VPA only reports recommendations; you apply them manually. |
auto | VPA updates requests/limits and restarts the pod. |
manual | VPA reports recommendations; you merge them into the pod spec. |
Typical launch flags (when installing via Helm or plain manifests):
--horizontal-pod-autoscaler-sync-period=30s \
--vertical-pod-autoscaler-mode=auto
A VPA Recommendation object:
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
spec:
targetRef:
apiVersion: "apps/v1"
kind: Deployment
name: api
updatePolicy:
updateMode: "Auto"
When VPA runs in auto mode, it patches the pod spec with learned values and triggers a restart. If the new requests exceed node capacity, the pod may be rescheduled or evicted by the Cluster Autoscaler.
Sharp edge: Running VPA in auto mode alongside HPA can create scaling oscillation. VPA rewrites the pod’s requests field, which the HPA then uses as the new baseline. If VPA raises requests faster than HPA can react, you get CPU‑usage sinusoids in monitoring. The usual fix is to keep VPA in manual mode and apply recommendations manually, or scope VPA to a subset of pods.
The CAS adds or removes nodes in the underlying node group based on pending pods and current node utilization. It respects pod requests when calculating fit.
Key behaviour flags (passed to the CAS binary or via cloud‑provider integration):
--scale-down-utilization-threshold=0.5 (default ~0.5): the fraction of node capacity that must be free before the autoscaler considers deleting a node. --node-group-auto-discovery=label (e.g., k8s.io/cluster-autoscaler/enabled or a custom tag) to scope which node groups it manages.If a pod is pending because no node satisfies its requests, the CAS adds a node (provisions a new VM into the managed node group). If a node is underutilized beyond the threshold after pod eviction, the CAS deletes it.
Spot or preemptible nodes require extra labels or taints to integrate. The CAS respects NoSchedule taints and PDBs when deciding whether a node can be drained.
Spot/preemptible VMs are offered by cloud providers at reduced cost but can be reclaimed with short notice. From Kubernetes’ perspective they are just nodes you can label, taint, and steer workloads onto.
A common pattern is to add a label during node‑group provisioning (via Terraform, Pulumi, or the cloud console) and then reference it in pod specs:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: k8s.io/spot
operator: In
values: ["true"]
To protect critical pods from landing on spot nodes, add a NoSchedule taint to the spot node group and a matching toleration on the pod:
tolerations:
- key: dedicated
operator: Equal
value: spot
effect: NoSchedule
When the spot VM is reclaimed, the cloud provider sends a termination notice (typically a 2‑minute warning on most platforms). Kubernetes nodes receive this as a node/pod‑terminating condition, which triggers the kubelet to mark pods as Terminating after the grace period.
Two mechanisms help pods survive or gracefully shut down when a spot node is cut.
kubectl edit pdb/api-pdb
# spec:
# minAvailable: 2
SIGTERM, you can register a signal handler that finishes in‑flight requests or database transactions before exiting. The kubelet sends SIGTERM to all containers in the pod after the pod’s terminationGracePeriodSeconds (default 30 s). If the process exits cleanly within that window, the pod terminates without triggering a forced SIGKILL.Common pitfall: A minAvailable: 1 PDB on a single‑replica deployment combined with a spot node that gets reclaimed immediately. The CAS cannot evict the node, the pod stays pending, and you get a stuck deployment. Either raise minAvailable to match replica count, or avoid spot nodes for single‑replica workloads.
The CAS’s --scale-down-utilization-threshold interacts with spot behaviour. A lower threshold (e.g., 0.3) means the CAS will keep nodes up longer, tolerating more idle capacity—useful when spot instances fluctuate. A higher threshold (0.8) causes faster node removal but risks oscillating if spot instances are reclaimed right after the CAS marks a node as underutilized.
In practice, teams set the threshold based on their spot‑instance replacement latency. If it takes 3‑5 minutes to spin a new spot node, a lower threshold gives the system time to provision without triggering a pod‑pending cascade.
kubectl get hpa shows DESIRED but CURRENT stays put, and you see no scaling activity. The error manifest is silent: pods keep running at current replicas, metrics simply aren’t reported. auto mode can fight each other. VPA rewrites the pod’s requests field, which the HPA then uses as the new baseline. If VPA raises requests faster than HPA can react, you get scaling oscillation that looks like CPU‑usage sinusoids in monitoring. The fix is usually to keep VPA in manual mode and apply recommendations manually, or scope VPA to a subset of pods. terminationGracePeriodSeconds or doesn’t handle SIGTERM, the kubelet sends SIGKILL after the grace period. The pod is abruptly killed, logs may be truncated, and in‑flight requests or database transactions can leave the system in an inconsistent state. Always pair spot nodes with a container‑level signal handler or an init container that backs off on SIGTERM. minAvailable: 1 PDB on a single‑replica deployment prevents the CAS from evicting a spot node, which blocks cluster scaling and leaves the pod stuck in Pending if the node is reclaimed. Either over‑provision replicas or use a different eviction strategy for critical single‑replica services. nodeAffinity or toleration rules. Pods that were scheduled on the old spot node get rescheduled elsewhere, potentially onto on‑demand nodes, inflating cost. Automate label injection via the node bootstrap script or a DaemonSet that patches new nodes. These edges aren’t theoretical—they’re the common paths that turn a “cost‑saving” node group into a production incident if you haven’t wired the surrounding guards.
This page was rewritten on 26 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy