Introduction

Kubernetes cost optimization fails when teams start with the discount and end with the outage. The order that works is measurement, right-sizing, provisioning, then price: find out which workloads consume the money, shrink their requests to what they actually use, let the provisioner pack nodes tightly, and only then move suitable workloads onto cheaper interruptible capacity. Each step makes the next one safer, and skipping to Spot first puts fragile workloads on fragile capacity.

Illustrative composite: a platform team cuts its EKS bill by moving everything to Spot in one change. Two weeks later a capacity reclaim takes out three nodes in one zone during a sale, replicas cannot reschedule fast enough, and checkout latency triples. The post-incident review finds the real waste was elsewhere: the checkout service requested 4 CPU per Pod and used 300m, so the cluster ran three times the nodes it needed on any capacity type. Right-sizing first would have cut the bill on on-demand capacity alone, and Spot would have been a second, calmer decision.

This guide runs the sequence with five tools that each own one layer: OpenCost for allocation, Goldilocks and VPA for right-sizing, Karpenter for provisioning and consolidation, and Spot for price. The Karpenter versus Cluster Autoscaler comparison covers the provisioning choice in depth if you have not made it yet.


1. Kubernetes cost optimization starts with requests, not instance prices

Kubernetes cost optimization begins with a scheduling fact: the scheduler places Pods by comparing their resource requests against node allocatable capacity, so requests are what you pay for. A Pod requesting 2 CPU and using 200m reserves 2 CPU of node capacity whether it uses it or not. Multiply that habit across a cluster and most of the bill is reservation, not consumption. Instance discounts applied to an over-requested cluster simply discount the waste.

This is why utilization reports mislead. A node at 30 percent CPU usage can be 95 percent requested, which means the scheduler sees it as full and the provisioner adds another node. The fix is not a cheaper node; it is honest requests. Memory behaves the same way with higher stakes, because over-requested memory blocks scheduling while under-requested memory gets Pods OOMKilled. CPU requests also set the guaranteed share under contention, so shrinking them blindly trades cost for noisy-neighbour latency. Right-sizing is a measurement exercise with a safety margin, not a race to the lowest number.

Frame the programme in layers so each tool's job stays clear. Allocation answers where the money went. Right-sizing answers how much each Pod should request. Provisioning answers which nodes should exist. Price answers what those nodes should cost. Teams get into trouble when one tool is asked to do another layer's job, such as expecting Karpenter to fix requests it merely reads, or expecting a cost dashboard to reduce a bill by being looked at.

Set the target in those terms. A credible first goal is cutting requested-but-unused capacity in the top namespaces and removing idle nodes, measured in node hours and allocated cost per namespace. Percentage savings claims vary wildly by starting point, so promise the mechanism and report the measured result rather than borrowing a vendor's number.


2. Kubernetes cost optimization with OpenCost: allocate before you optimise

Kubernetes cost optimization needs allocation before optimisation, because you cannot fix what you cannot attribute. OpenCost, the CNCF project originally built by Kubecost, breaks cluster cost down by namespace, controller, Pod and label using Prometheus metrics and cloud pricing data. Its allocation model charges each workload for the larger of what it requested and what it used, which is exactly the incentive you want: over-requesting shows up on the owning team's line, not hidden in a shared pool.

Install it against the Prometheus you already run, then read the two numbers that matter. Allocated cost by namespace tells you which teams own the bill. Idle cost, returned when you include idle capacity in the query, tells you how much node capacity nobody requested or used. Those two numbers separate the two diseases: high allocated cost with low usage means right-sizing work, while large idle cost means provisioning and consolidation work. Treating one disease with the other's medicine wastes a quarter.

bash
helm repo add opencost-charts https://opencost.github.io/opencost-helm-chart
helm repo update
helm install opencost opencost-charts/opencost   --namespace opencost --create-namespace -f values.yaml

kubectl port-forward -n opencost svc/opencost 9003:9003
curl 'http://localhost:9003/allocation?window=7d&aggregate=namespace&includeIdle=true'
curl 'http://localhost:9003/allocation?window=7d&aggregate=controller&filter=controllerKind%3A%22deployment%22'

Treat the first report as a ranking, not an invoice. Verify how node prices are sourced, especially whether Spot and discounted rates are reflected, and reconcile the total against the cloud bill before quoting numbers to finance. Label discipline decides whether allocation is useful: namespaces per team or product, and consistent app labels, turn OpenCost output into chargeback conversations instead of arguments. Pair it with the guardrails in the ResourceQuota and LimitRange guide so allocation has enforcement behind it.


3. Kubernetes cost optimization with Goldilocks: recommendations without automation risk

Kubernetes cost optimization gets its safest right-sizing wins from Goldilocks, the Fairwinds tool that creates Vertical Pod Autoscaler objects in recommendation-only mode for workloads in labelled namespaces and presents the recommendations per container. It needs the VPA recommender, not the updater or admission controller, so nothing changes automatically. That separation is the point: you get data-driven request suggestions with zero risk of a controller evicting production Pods at 3 a.m.

Run it for at least one full business cycle, ideally two weeks, so recommendations see peaks, batch windows and weekend troughs. A recommendation built on a quiet Tuesday will starve a Monday peak. Then work the list in allocated-cost order from OpenCost: the top namespaces first, the largest request-versus-usage gaps first. Apply changes through your normal GitOps path, one service at a time, watching latency, throttling and OOM events as requests come down.

bash
helm repo add fairwinds-stable https://charts.fairwinds.com/stable
helm install goldilocks fairwinds-stable/goldilocks   --namespace goldilocks --create-namespace
kubectl label namespace payments goldilocks.fairwinds.com/enabled=true
kubectl get vpa -n payments
kubectl describe vpa <vpa-name> -n payments

Read recommendations with judgement. The VPA recommender works from historical usage percentiles, so it cannot know about a marketing launch next week, a data backfill, or a memory leak you are about to fix. Keep headroom above the recommendation for memory especially, because memory cannot be throttled the way CPU can; exceeding a memory limit kills the container. CPU recommendations can sit closer to observed usage since the penalty is throttling, which is visible and recoverable. The HPA versus VPA guide explains how these recommendations interact with horizontal scaling before you combine them.


4. Kubernetes cost optimization with VPA: when to automate and when not to

Kubernetes cost optimization can go further with VPA in an updating mode, but automation changes the risk profile. In Recreate mode the VPA evicts Pods so replacements start with new resource values; the older Auto mode is an alias for Recreate in current VPA versions. That means automated right-sizing is automated eviction, and it is only safe where PodDisruptionBudgets, readiness probes and replica counts already make evictions boring. Stateless services with several replicas are candidates. Single-replica services, stateful workloads and anything with fragile startup are not.

Respect the known conflicts. Do not let VPA and an HPA both act on CPU or memory for the same workload, because the HPA computes utilization against the request that VPA keeps changing, and the two controllers chase each other. The common production pattern is VPA in recommendation mode feeding human-approved changes, HPA handling replica count, and VPA automation reserved for batch and internal workloads where an eviction costs nothing. The HPA v2 tutorial covers the HPA side of that division.

If you do automate, bound it. Resource policies with minimum and maximum allowed values per container stop a bad recommendation from shrinking a service into failure or inflating it into waste. Roll out per namespace, watch eviction rates and error budgets, and keep a one-line rollback that returns the VPA to recommendation mode. Automation that cannot be switched off quickly will be switched off permanently after its first incident.

yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: checkout-api
  namespace: payments
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: checkout-api
  updatePolicy:
    updateMode: "Off"
  resourcePolicy:
    containerPolicies:
      - containerName: api
        minAllowed:
          cpu: "100m"
          memory: "128Mi"
        maxAllowed:
          cpu: "2"
          memory: "2Gi"
        controlledResources: ["cpu", "memory"]

Start every workload at updateMode Off, which is recommendation-only, and promote individual services only after their recommendations have proven stable across a peak cycle. That promotion list, reviewed monthly, is the difference between a right-sizing programme and a random eviction generator.


5. Kubernetes cost optimization with Karpenter: provision nodes that fit the work

Kubernetes cost optimization at the provisioning layer is where Karpenter earns its place. Instead of scaling fixed node groups, Karpenter watches for unschedulable Pods, picks instance types that fit their requests and constraints, launches nodes just in time, and consolidates underused nodes by moving Pods and terminating the emptied machines. Right-sized requests make this dramatically more effective, because bin-packing works on requests: honest requests pack tightly, inflated requests strand capacity on every node.

Design NodePools around workload classes, not around teams. A general pool for stateless services, a Spot pool for interruption-tolerant work, and separate pools for special hardware or compliance constraints keep the policy legible. Set limits so a runaway scaler cannot provision the account empty, and choose a consolidation policy that matches your disruption tolerance. Consolidation is where the money is after right-sizing: nodes that drift to 30 percent requested get emptied and terminated instead of idling until someone notices.

yaml
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
  name: general
spec:
  template:
    spec:
      requirements:
        - key: karpenter.sh/capacity-type
          operator: In
          values: ["on-demand", "spot"]
        - key: kubernetes.io/arch
          operator: In
          values: ["amd64", "arm64"]
        - key: karpenter.sh/instance-category
          operator: In
          values: ["c", "m", "r"]
      nodeClassRef:
        group: karpenter.k8s.aws
        kind: EC2NodeClass
        name: default
  limits:
    cpu: "500"
    memory: "1000Gi"
  disruption:
    consolidationPolicy: WhenEmptyOrUnderutilized
    consolidateAfter: 1m

The Karpenter NodePool patterns guide goes deeper on consolidation, expiry and Spot pool design. Two cautions belong here. First, Karpenter provisions for the requests it receives, so it amplifies whatever right-sizing discipline you have; fix requests first. Second, consolidation moves Pods, so the same PDB and readiness discipline that makes drains safe makes consolidation safe. Provisioning automation without disruption guardrails is just faster churn.


6. Kubernetes cost optimization with Spot: cheap capacity for tolerant workloads

Kubernetes cost optimization reaches its largest per-node discounts with Spot capacity, and its largest risks. Spot instances are spare cloud capacity sold at a steep discount that the provider can reclaim with short notice; on AWS the interruption notice is two minutes. That trade is excellent for workloads that tolerate losing a node at any moment and terrible for workloads that do not. The engineering work is sorting your fleet into those two piles honestly.

Make Spot safe by construction. Run Spot in its own NodePool with a taint so only workloads that explicitly tolerate interruption land there, and require a node selector as well, because a toleration permits scheduling without attracting Pods. Diversify instance types and zones so a single capacity pool reclaiming does not take every replica at once. Keep replicas spread with topology constraints, keep PodDisruptionBudgets honest, and make sure the workload handles SIGTERM gracefully inside the notice window. Karpenter consumes interruption signals and drains proactively, which turns a reclaim into an orderly reschedule for well-built services.

yaml
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
  name: spot-batch
spec:
  template:
    metadata:
      labels:
        workload-class: spot-tolerant
    spec:
      taints:
        - key: spot
          effect: NoSchedule
      requirements:
        - key: karpenter.sh/capacity-type
          operator: In
          values: ["spot"]
        - key: karpenter.sh/instance-category
          operator: In
          values: ["c", "m", "r"]
        - key: karpenter.sh/instance-generation
          operator: Gt
          values: ["5"]
      nodeClassRef:
        group: karpenter.k8s.aws
        kind: EC2NodeClass
        name: default
  limits:
    cpu: "300"
  disruption:
    consolidationPolicy: WhenEmptyOrUnderutilized
    consolidateAfter: 1m

Good Spot candidates are batch jobs, CI runners, stateless workers behind queues, and services with many replicas and fast startup. Poor candidates are single-replica services, stateful primaries, and anything whose recovery time exceeds the interruption notice. Test the failure: terminate a Spot node in staging and watch rescheduling, latency and error rates. A workload that has never survived a node loss in staging has not earned Spot in production, whatever the discount.


7. Kubernetes cost optimization decision table: which lever for which waste

Kubernetes cost optimization goes wrong when a lever is applied to waste it cannot fix. The table below maps each kind of waste to the layer that owns it, the tool that addresses it, and the signal that proves it worked. Use it to sequence work and to push back on requests that start at the wrong layer.

Waste signal Owning layer Lever Proof it worked
High allocated cost, low usage Requests Goldilocks and VPA right-sizing Requested capacity falls, node count follows
Large idle cost in OpenCost Provisioning Karpenter consolidation, smaller pools Idle cost and node hours fall
Nodes half-empty but fully requested Requests plus packing Right-size, then consolidate Requested utilization rises per node
Expensive on-demand nodes for batch work Price Spot NodePool with taints Batch cost per job falls, completions hold
Dev clusters running all night Scheduling Scale-to-zero and scheduled shutdown Non-prod node hours fall outside work hours
Cost concentrated in one namespace Ownership Allocation, quotas, team review That namespace's allocated cost trends down
Savings undone by growth in a month Governance Budgets, alerts, monthly review Cost per request or per user stays flat

Two sequencing rules sit behind the table. First, price levers come last because they multiply whatever waste remains; a Spot discount on an over-requested fleet still leaves the over-request. Second, governance is a lever, not paperwork. Without budgets and a monthly review of allocation trends, right-sizing decays as new services ship with copied requests, and the programme becomes an annual cleanup instead of a standing property of the platform.

The table also settles tool arguments. OpenCost and Goldilocks do not compete; one attributes cost, the other recommends requests. Karpenter does not replace either; it provisions for the requests they shape. Spot does not replace Karpenter; it is a capacity type Karpenter can choose. Layered tools compose, and the composition is the programme.


8. Kubernetes cost optimization troubleshooting matrix: when savings cause symptoms

Kubernetes cost optimization changes production behaviour, so the programme needs a troubleshooting matrix for the symptoms it can cause. Each row pairs a symptom after a cost change with the likely cause, the confirming check, and the corrective move. Work it before reverting blindly, because most symptoms have a targeted fix that keeps the saving.

Symptom Likely cause Confirm with Fix
OOMKilled after request reduction Memory request or limit cut too far Pod events, memory usage vs new values Raise memory with headroom, re-measure over a peak
CPU throttling and latency rise CPU request cut below working set Throttling metrics, latency by Pod Raise CPU request, keep limit policy deliberate
HPA behaviour changed after VPA work HPA and VPA both acting on CPU or memory HPA targets vs VPA mode VPA to recommendation mode, HPA owns replicas
Pods Pending after consolidation Pool limits or constraints too tight Pod events, NodePool limits Raise limits or widen instance requirements
Eviction storms during consolidation PDBs missing or too loose Eviction events, PDB status Add PDBs, slow consolidation, spread replicas
Spot reclaim causes errors Workload not interruption-tolerant Interruption events vs error timeline Move workload off Spot, fix graceful shutdown
Cost did not fall after right-sizing Nodes not consolidating or pools fixed OpenCost idle cost, node count trend Enable consolidation, shrink fixed node groups
Allocation total disagrees with bill Pricing source or idle handling wrong Reconcile OpenCost total with cloud bill Fix price source, include idle deliberately

Read the matrix with the change log open. Cost symptoms correlate with specific changes: a request reduction on Tuesday, a consolidation policy change on Thursday. Correlate the symptom timestamp with the programme's changes before blaming the application, and correlate with application deploys before blaming the programme. The discipline is the same as any incident: evidence first, then the smallest corrective change.

Keep the matrix next to the rollout plan, and pre-agree the rollback for each lever: restore previous requests from Git, return VPA to recommendation mode, pause consolidation, or drain the Spot pool. Rollbacks decided in advance get executed calmly; rollbacks invented during an incident get executed twice.


9. Kubernetes cost optimization guardrails: quotas, budgets and disruption safety

Kubernetes cost optimization survives contact with an organisation only if guardrails make the cheap path the easy path. Namespace ResourceQuotas cap total requests per team so one service cannot silently consume the savings another team produced. LimitRanges default requests and limits for containers that forget them, which prevents the unbounded Pod that later becomes a pressure incident. Admission policies can require requests on every container and reject memory limits below requests. These controls are unglamorous and they are what keep right-sizing from decaying.

Disruption safety is the other guardrail family. PodDisruptionBudgets on every multi-replica service, readiness probes that tell the truth, graceful termination handling, and topology spread across zones and nodes. Consolidation, Spot reclaims and node upgrades all spend from the same disruption budget. A platform that cannot drain a node safely cannot consolidate nodes, cannot use Spot aggressively, and cannot upgrade without drama. Fix disruption safety once and every cost lever gets safer. The EKS versus GKE versus AKS guide notes where managed platforms differ on these mechanics.

Financial guardrails close the loop. Budgets per namespace or product with alerts at thresholds, a monthly review where allocation trends are read alongside traffic growth, and a cost-per-unit metric such as cost per thousand requests so growth is not mistaken for waste. Commitments such as savings plans come last, after utilization has been stable for a month or more, because a commitment bought against an over-requested baseline locks in the waste at a discount.

Write the guardrails into the platform's golden paths: service templates with sane requests, VPA recommendation objects by default, PDBs in the template, and Spot tolerations only in the batch template. Engineers copy templates far more reliably than they follow wikis, so the template is where cost discipline actually lives.


10. Kubernetes cost optimization rollout plan: four weeks without heroics

Kubernetes cost optimization should roll out as a programme with weekly gates, not as a single heroic change. Week one is measurement: OpenCost running, pricing reconciled against the bill, namespaces labelled, and the top ten allocated-cost workloads identified. No requests change yet. The output is a ranked list and a baseline, agreed with the teams who own the top entries.

Week two is right-sizing in recommendation mode. Goldilocks labels go on the top namespaces, recommendations accumulate across real traffic, and the first changes ship through GitOps for the clearest cases: large gaps, stateless services, strong replica counts. Watch throttling, OOM events and latency per change. Week three is provisioning: Karpenter pools reviewed or introduced, consolidation enabled with conservative settings, fixed node groups shrunk as consolidation proves itself. Week four is price: the Spot pool opens for validated batch and worker workloads, interruption handling is tested, and commitments are discussed only if utilization has stabilised.

Each week has a stop condition. Measurement stops if pricing cannot be reconciled. Right-sizing pauses for a service if error budgets burn. Consolidation slows if evictions correlate with latency. Spot closes for a workload that fails its interruption test. Stop conditions written in advance turn arguments into observations, which is what makes the programme survivable by the teams it touches.

Report weekly in the units finance and engineering both understand: allocated cost by namespace, idle cost, node hours, and cost per unit of traffic, alongside error budget consumption. Savings that cost reliability will show up in that report, and so will reliability preserved while savings land. That pairing is the programme's licence to continue.


11. Kubernetes cost optimization use cases: platform, product and interview angles

Kubernetes cost optimization serves three audiences with the same layered model. Platform teams use it to design golden paths: templates with honest requests, recommendation-mode VPA by default, NodePools per workload class, and allocation dashboards that make cost a property of every deploy. Their success metric is not a one-time saving but a cost-per-unit curve that stays flat as traffic grows.

Product and engineering leadership use the allocation layer. OpenCost by namespace or label turns the cloud bill into per-product and per-feature economics, which changes roadmap conversations: a feature that costs more to run than it returns becomes visible while it is still cheap to fix. The discipline is to read allocation as a ranking with reconciled totals, not as a precise invoice per Pod, and to pair it with traffic data so growth is not punished as waste.

In interviews and system-design discussions, cost optimization is a standard probe of operational maturity. The strong answer sequences the layers: measure with allocation, right-size requests, provision with bin-packing and consolidation, then buy cheaper capacity for tolerant workloads, all behind PDB and quota guardrails. The weak answer jumps straight to Spot instances and reserved pricing. Practise saying why requests drive cost, why VPA and HPA must not fight over the same signal, and why consolidation needs disruption safety. Those three sentences carry most follow-up questions an interviewer can ask.

Each audience reads the same numbers at a different altitude, which is why the layered model is worth learning once and reusing everywhere. The platform engineer, the product manager and the interview candidate are all answering one question: where does the money go, and which layer owns the fix?

Kubernetes cost optimization has honest limits. Allocation models are approximations: shared costs, idle capacity and pricing nuances mean OpenCost ranks workloads reliably but does not reproduce the invoice to the cent. Recommendations are backward-looking: VPA learns from history and cannot foresee launches, backfills or leaks. Spot capacity is not guaranteed capacity, and consolidation trades disruption for savings at a rate each organisation must choose. Managed platforms differ in pricing and provisioning mechanics, so the sequence transfers but the exact settings do not.

There is also a floor below which optimisation becomes false economy. Requests cut into the working set buy throttling and OOM kills. Consolidation tuned too aggressively buys churn. Spot pushed onto intolerant workloads buys incidents. The guardrails in this guide exist to mark that floor with evidence: error budgets, throttling metrics, eviction rates and interruption tests. When those signals move, the saving is overpriced and the lever should back off.

The senior takeaways are short. Requests are what you pay for, so measure allocation and right-size before touching instance prices. Keep VPA in recommendation mode until evictions are boring, and never let VPA and HPA fight over the same signal. Let Karpenter pack and consolidate what honest requests make packable. Put Spot behind taints, diversity and interruption tests. Govern with quotas, budgets and a monthly review so savings persist. Done in that order, Kubernetes cost optimization is not a quarterly cleanup; it is how the platform normally runs.

Frequently Asked Questions

What is Kubernetes cost optimization in practice?

It is a layered programme: measure cost allocation per workload, right-size resource requests to actual usage, provision nodes that pack tightly and consolidate when underused, and move interruption-tolerant workloads to cheaper capacity such as Spot, all behind quota and disruption guardrails.

Why does Kubernetes cost optimization start with requests?

Because the scheduler reserves capacity by requests, so you pay for what Pods request rather than what they use. A Pod requesting 2 CPU and using 200m blocks 2 CPU of node capacity. Fixing inflated requests reduces node count before any instance discount is applied.

How does OpenCost help Kubernetes cost optimization?

OpenCost attributes cluster cost by namespace, controller, Pod and label, charging each workload for the larger of its request and usage. High allocated cost with low usage points at right-sizing, while large idle cost points at provisioning and consolidation. Reconcile its pricing against the cloud bill before quoting totals.

Is Goldilocks safe for Kubernetes cost optimization in production?

Yes, because Goldilocks runs VPA in recommendation-only mode: it suggests requests per container and changes nothing automatically. Let recommendations accumulate across a full traffic cycle, apply changes through GitOps one service at a time, and keep memory headroom above the suggestion.

Should VPA automate Kubernetes cost optimization changes?

Only where evictions are already safe. VPA in Recreate mode evicts Pods to apply new values, so it needs PodDisruptionBudgets, honest readiness probes and several replicas. Never let VPA and an HPA both act on CPU or memory for the same workload. Recommendation mode is the safe default.

How does Karpenter improve Kubernetes cost optimization?

Karpenter provisions nodes sized to pending Pod requests, bin-packs workloads onto fewer instances, and consolidates underused nodes by moving Pods and terminating emptied machines. It amplifies request discipline: honest requests pack tightly, while inflated requests strand capacity on every node it launches.

Which workloads suit Spot in Kubernetes cost optimization?

Batch jobs, CI runners, queue workers and multi-replica stateless services with fast startup and graceful shutdown. Keep Spot in a tainted NodePool with diverse instance types and zones, require explicit tolerations and selectors, and test node loss in staging before trusting a workload to it.

⚡ KUBERNETES SCENARIO INTERVIEW PREP

Preparing for Senior Platform & SRE Interviews

Practice real-world cluster triage, RBAC debugging, and pod scheduling scenarios in our Kubernetes scenario interview questions hub.

Explore Interview Scenarios →