How to Control Kubernetes Costs: Resource Limits, Autoscaling, and Spot Nodes

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.

Setting Resource Requests and Limits

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"

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.

Autoscale Workloads

Autoscaling operates at two levels: per‑pod (VPA/HPA) and per‑node (Cluster Autoscaler). Each has distinct triggers, configuration keys, and failure modes.

Horizontal Pod Autoscaler (HPA)

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.

Vertical Pod Autoscaler (VPA)

VPA learns request/limit recommendations and can auto‑apply them. It runs as a deployment and watches container metrics. Three modes control behaviour:

ModeAction
offVPA only reports recommendations; you apply them manually.
autoVPA updates requests/limits and restarts the pod.
manualVPA 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.

Cluster Autoscaler (CAS)

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):

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.

Use Spot or Preemptible Nodes

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.

Labeling and tainting spot nodes

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.

Handling pod termination on spot eviction

Two mechanisms help pods survive or gracefully shut down when a spot node is cut.

  1. Pod Disruption Budget (PDB) – Ensures a minimum number of replicas remain available during voluntary evictions. The CAS respects PDBs when draining a spot node, so it won’t delete a node if doing so would violate the PDB, forcing it to wait or add another node first.
   kubectl edit pdb/api-pdb
   # spec:
   #   minAvailable: 2
  1. Graceful shutdown signal handling – If your workload handles 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.

Cluster‑wide scaling triggers with spot

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.

Sharp Edges: What Silently Fails

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.