✓Kubernetes cluster (v1.24+), Helm v3, kubectl, AWS account (for Karpenter and spot), Prometheus and Grafana (optional but recommended), basic understanding of Kubernetes resource requests and limits.
✦ Definition~90s read
What is Kubernetes Cost Optimization?
Kubernetes cost optimization is the practice of reducing cloud spend by right-sizing workloads, eliminating waste, and leveraging spot instances without sacrificing reliability. It matters because Kubernetes clusters often run at 30-50% utilization, wasting millions annually. Use it when your cloud bill exceeds $10k/month or you're scaling beyond 10 nodes.
★
Think of Kubernetes Cost Optimization — Kubecost, Karpenter, Spot like a tool in your DevOps toolkit — once you understand what it does and when to reach for it, managing Kubernetes clusters becomes second nature.
Plain-English First
Think of Kubernetes Cost Optimization — Kubecost, Karpenter, Spot like a tool in your DevOps toolkit — once you understand what it does and when to reach for it, managing Kubernetes clusters becomes second nature.
Welcome to Kubernetes Cost Optimization — Kubecost, Karpenter, Spot. We'll break this down from first principles.
Kubernetes abstracts infrastructure, making it easy to deploy more resources than needed. The default behavior of most operators and Helm charts is to request far more CPU and memory than necessary. Without cost visibility, teams accumulate orphaned resources, over-provisioned nodes, and idle workloads. The result: cloud bills that grow linearly with cluster size, not actual utilization. In production, we've seen teams double their AWS bill by simply enabling cluster autoscaler without limits. The root cause is a lack of feedback loops — developers don't see the cost impact of their resource requests.
check-overprovisioning.shBASH
1
2
3
kubectl top pods -A --sort-by=cpu | head -20
# Compare to resource requests:
kubectl get pods -A -o json | jq '.items[] | {name: .metadata.name, requests: .spec.containers[].resources.requests}'
Output
NAMESPACE POD CPU(cores) MEMORY(bytes)
default app-1 50m 128Mi
default app-2 200m 512Mi
# Requests often 2-4x actual usage
⚠ The 2x Rule
If your pod CPU request is more than 2x its actual peak usage, you're paying for idle capacity. Enforce resource quotas to cap waste.
📊 Production Insight
In one incident, a team deployed a Redis cluster with 8 CPU requests per pod, but actual usage was 0.2 cores. The fix: right-sizing saved $4k/month.
🎯 Key Takeaway
Without visibility, Kubernetes cost waste is invisible until the bill arrives.
Kubecost: Real-Time Cost Visibility and Allocation
Kubecost is an open-source tool that maps Kubernetes resource usage to cloud costs. It breaks down spend by namespace, deployment, label, or pod. Install it via Helm, and within minutes you get a dashboard showing cost per team, per service, and per cluster. The key metric is 'efficiency' — the ratio of actual usage to requested resources. Kubecost also provides recommendations for right-sizing requests and limits. In production, we use Kubecost to generate monthly chargebacks to engineering teams. Without it, cost allocation is guesswork. Kubecost integrates with AWS, GCP, and Azure to pull real-time pricing.
Release "kubecost" has been upgraded. Happy Helming!
# Then open http://localhost:9090
🔥Chargeback Model
Use Kubecost's allocation API to generate monthly reports per namespace. Automate email reports to team leads.
📊 Production Insight
We set up Kubecost alerts for when a namespace's daily cost exceeds $100. This caught a runaway CI job that cost $2k in one day.
🎯 Key Takeaway
Kubecost gives you the data to make informed cost decisions.
thecodeforge.io
Kubernetes Cost Optimization
Right-Sizing Workloads with Kubecost Recommendations
Kubecost's right-sizing recommendations analyze historical usage (default 7 days) and suggest optimal CPU/memory requests. Apply them via the UI or programmatically using the API. The recommendation engine uses the 95th percentile of usage to avoid under-provisioning. In production, we batch-apply recommendations during off-peak hours. A common pitfall: blindly applying recommendations without considering traffic spikes. Always set a buffer (e.g., 20% above the 95th percentile). Kubecost also supports 'request sizing' for DaemonSets and sidecars.
apply-recommendations.shBASH
1
2
3
4
5
6
7
8
9
10
# Get recommendations via API
curl -s "http://localhost:9090/model/savings/requestSizing" | jq '.recommendations'
# Apply using kubecost-recommender (custom script)
# Example output:
{
"namespace": "production",
"container": "app",
"currentRequest": {"cpu": "500m", "memory": "512Mi"},
"recommendedRequest": {"cpu": "250m", "memory": "256Mi"}
}
Output
{
"recommendations": [
{
"namespace": "default",
"pod": "nginx-xxx",
"container": "nginx",
"current": {"cpu": "500m", "memory": "512Mi"},
"recommended": {"cpu": "100m", "memory": "128Mi"}
}
]
}
⚠ Don't Auto-Apply Without Review
Always review recommendations for stateful workloads. A sudden memory reduction can cause OOM kills.
📊 Production Insight
We reduced a 50-node cluster to 30 nodes by right-sizing all workloads. Savings: $15k/month.
🎯 Key Takeaway
Right-sizing is the highest ROI cost optimization action.
Karpenter: Dynamic Node Provisioning for Cost Efficiency
Karpenter is an open-source node autoscaler for Kubernetes that launches just-in-time nodes based on pod resource requirements. Unlike the traditional Cluster Autoscaler, Karpenter works at the pod level, not the node group level. It can launch different instance types (including spot) and terminates nodes when they're no longer needed. Karpenter reduces waste by bin-packing pods tightly and avoiding over-provisioning. In production, Karpenter can cut node costs by 30-50% compared to static node groups. It supports AWS, and soon GCP and Azure.
NodePool created. Karpenter will now launch nodes based on pending pods.
💡Consolidation Policy
Set consolidationPolicy: WhenUnderutilized to automatically terminate nodes with low utilization and re-schedule pods onto cheaper instances.
📊 Production Insight
We saw a 40% reduction in node count after switching from Cluster Autoscaler to Karpenter. The key was enabling spot diversification.
🎯 Key Takeaway
Karpenter eliminates node-level waste by provisioning exactly what you need.
Spot Instances: The Biggest Cost Saver with Karpenter
Spot instances are spare cloud compute capacity offered at up to 90% discount. Karpenter can automatically use spot instances for interruptible workloads. The risk: spot instances can be reclaimed with 2-minute notice. Mitigate by using pod disruption budgets, graceful shutdown hooks, and multi-az deployments. Karpenter's spot-to-spot consolidation ensures you always use the cheapest spot instance type available. In production, we run 80% of our batch jobs and stateless services on spot. The key is to never run stateful workloads (databases, Kafka) on spot without proper replication.
Deployment created. Pods will be scheduled on spot instances if available.
⚠ Spot Reclamation Handling
Always implement a preStop hook and use PDBs. Without them, spot interruptions cause cascading failures.
📊 Production Insight
A team lost a Kafka broker on spot because they had no PDB. The cluster went down for 10 minutes. Lesson: never run stateful workloads on spot without replication.
🎯 Key Takeaway
Spot instances can cut compute costs by 70% when used correctly.
Combining Karpenter and Spot for Maximum Savings
The real power is using Karpenter with spot instances as the default capacity type. Configure Karpenter to prefer spot but fall back to on-demand if spot is unavailable. This ensures availability while maximizing savings. Use node pools with different instance families to increase spot capacity pool diversity. In production, we set spot allocation strategy to 'lowest-price' but with a cap to avoid using extremely cheap but unreliable instances. Monitor spot interruption rates via Karpenter metrics. The combination of Karpenter + spot typically yields 50-70% savings over on-demand only.
Two node pools created. Karpenter will try spot first, then on-demand.
🔥Fallback Strategy
Always have an on-demand fallback node pool with lower priority to prevent pods from staying pending.
📊 Production Insight
We run 90% spot for stateless workloads. The 10% on-demand acts as a safety net during spot shortages.
🎯 Key Takeaway
Spot-first with on-demand fallback is the optimal cost strategy.
Pod Disruption Budgets and Graceful Shutdowns
Pod Disruption Budgets (PDBs) ensure a minimum number of pods remain available during voluntary disruptions (node drains, spot interruptions). For spot instances, PDBs are critical. Set minAvailable or maxUnavailable based on your application's redundancy. Combine with preStop hooks to gracefully drain connections. In production, we use PDBs with maxUnavailable: 1 for deployments with 3+ replicas. For stateful workloads, use pod anti-affinity to spread across nodes. Without PDBs, a spot interruption can take down all replicas.
PDB created. At most 1 pod can be unavailable at a time.
💡PDB for StatefulSets
For StatefulSets, use minAvailable: 2 to ensure quorum. Test with chaos engineering.
📊 Production Insight
We had a PDB misconfigured with maxUnavailable: 0, which blocked all node drains. The cluster became stuck. Always allow at least 1 disruption.
🎯 Key Takeaway
PDBs are non-negotiable for spot workloads.
thecodeforge.io
Kubernetes Cost Optimization
Monitoring and Alerting for Cost Anomalies
Cost optimization is not a one-time effort. Set up monitoring and alerting for cost anomalies. Use Kubecost alerts for daily budget thresholds, spot interruption rates, and node utilization. Integrate with PagerDuty or Slack. In production, we have alerts for: namespace cost > $500/day, spot interruption rate > 5%, and node utilization < 20%. Also monitor Karpenter metrics like nodes created, terminated, and spot interruption count. Use Prometheus and Grafana for dashboards. Without monitoring, cost savings degrade over time as teams add new workloads.
Alert configured. Kubecost will send Slack notifications when a namespace exceeds $500/day.
⚠ Alert Fatigue
Start with high thresholds and tune down. Too many alerts lead to ignored notifications.
📊 Production Insight
We missed a $10k overspend because the alert threshold was set too high. Now we use tiered alerts: warning at 80%, critical at 100%.
🎯 Key Takeaway
Continuous monitoring prevents cost regressions.
Advanced: Node Consolidation and Bin Packing
Karpenter's consolidation feature automatically terminates underutilized nodes and reschedules pods onto cheaper or more efficient instances. This is called 'bin packing'. Enable consolidationPolicy: WhenUnderutilized to trigger consolidation when a node's utilization drops below a threshold. Karpenter also supports 'do not consolidate' for nodes with critical workloads. In production, we use consolidation aggressively for spot nodes but conservatively for on-demand. Monitor consolidation events to ensure they don't cause cascading restarts. Bin packing can reduce node count by 20-30%.
Node pool with aggressive consolidation. Nodes will be consolidated after 5 minutes of underutilization.
🔥Consolidation Delay
Set consolidateAfter to at least 5 minutes to avoid flapping during short traffic dips.
📊 Production Insight
Aggressive consolidation once caused a thundering herd of pod restarts. We added a 10-minute cooldown to prevent that.
🎯 Key Takeaway
Consolidation is the key to maintaining low node counts.
Cost Optimization for Stateful Workloads
Stateful workloads (databases, message queues) are harder to optimize because they require persistent storage and stable nodes. Use local SSDs with node affinity, or EBS volumes with volume binding mode WaitForFirstConsumer. For cost savings, consider using spot instances for read replicas or non-leader nodes. Use Karpenter's node templates to attach specific volumes. In production, we run Cassandra on spot for non-leader nodes, saving 60% on compute. The leader node runs on on-demand. Always test with chaos engineering before production rollout.
StatefulSet created. Pods will be scheduled on spot nodes.
⚠ Stateful on Spot?
Only use spot for stateful workloads if you have replication and can tolerate node loss. Test with chaos engineering.
📊 Production Insight
We lost a Cassandra node on spot and the cluster auto-repaired. But the repair caused a 20% latency spike. We now use PDBs and anti-affinity.
🎯 Key Takeaway
Stateful workloads can use spot with proper replication and testing.
Governance: Enforcing Cost Policies with OPA/Gatekeeper
To prevent cost waste from the start, enforce policies using Open Policy Agent (OPA) or Gatekeeper. For example, require all pods to have resource limits, enforce minimum node count, or block expensive instance types. In production, we have policies that: require CPU and memory limits, block instance types larger than m5.xlarge, and enforce spot-only for non-production namespaces. Gatekeeper can also validate Karpenter NodePool configurations. Without governance, cost optimization is reactive.
Constraint created. All pods must have resource limits and requests.
💡Start with Audit Mode
Run Gatekeeper in audit-only mode first to see violations without blocking deployments.
📊 Production Insight
We blocked a team from deploying a 32-core pod by accident. Gatekeeper saved us $5k/month.
🎯 Key Takeaway
Policy enforcement prevents cost drift.
Karpenter vs Cluster AutoscalerDynamic provisioning approaches for cost savingsKarpenterCluster AutoscalerNode Provisioning SpeedSeconds to minutesMinutes to tens of minutesInstance DiversityMultiple instance types per node groupSingle instance type per node groupSpot IntegrationNative spot with fallback to on-demandRequires separate spot node groupsCost OptimizationSelects cheapest available instanceLimited to predefined node groupsConfiguration ComplexitySimple provisioning specsComplex node group managementTHECODEFORGE.IO
thecodeforge.io
Kubernetes Cost Optimization
Putting It All Together: A Production Cost Optimization Pipeline
The ultimate setup: Kubecost for visibility and recommendations, Karpenter with spot-first node pools, PDBs for resilience, Gatekeeper for governance, and Prometheus/Grafana for monitoring. Automate the feedback loop: Kubecost recommendations trigger a CI job that updates resource requests, which then get deployed. Use Karpenter's metrics to adjust spot diversification. In production, this pipeline reduced our monthly bill by 60% over 6 months. The key is to iterate: start with visibility, then right-size, then spot, then consolidate. Don't try everything at once.
Right-Sizing Workloads with Kubecost Recommendations
karpenter-provisioner.yaml
apiVersion: karpenter.sh/v1beta1
Karpenter
spot-workload.yaml
apiVersion: apps/v1
Spot Instances
karpenter-spot-config.yaml
apiVersion: karpenter.sh/v1beta1
Combining Karpenter and Spot for Maximum Savings
pdb.yaml
apiVersion: policy/v1
Pod Disruption Budgets and Graceful Shutdowns
kubecost-alert.yaml
apiVersion: v1
Monitoring and Alerting for Cost Anomalies
consolidation-policy.yaml
apiVersion: karpenter.sh/v1beta1
Advanced
statefulset-spot.yaml
apiVersion: apps/v1
Cost Optimization for Stateful Workloads
gatekeeper-constraint.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
Governance
cost-pipeline.yaml
name: Cost Optimization
Putting It All Together
Key takeaways
1
Visibility First
Without Kubecost or similar tools, you can't optimize what you can't see. Start with cost allocation.
2
Right-Sizing is Highest ROI
Adjusting resource requests to match actual usage can reduce node count by 30-50%.
3
Spot Instances with Karpenter
Use spot as default with on-demand fallback. Karpenter automates the complexity.
4
Governance Prevents Regressions
Enforce resource limits and instance type restrictions with OPA/Gatekeeper.
INTERVIEW PREP · PRACTICE MODE
Interview Questions on This Topic
Q01JUNIOR
What is the difference between Karpenter and Cluster Autoscaler?
Q02JUNIOR
Can I use spot instances for stateful workloads?
Q03JUNIOR
How do I get started with Kubecost?
Q01 of 03JUNIOR
What is the difference between Karpenter and Cluster Autoscaler?
ANSWER
Cluster Autoscaler works at the node group level, adding or removing nodes based on pending pods. Karpenter works at the pod level, provisioning the exact instance types needed. Karpenter is faster, m
Q02 of 03JUNIOR
Can I use spot instances for stateful workloads?
ANSWER
Yes, but only if you have replication, pod disruption budgets, and graceful shutdown handling. Stateful workloads like databases should have leader nodes on on-demand and replicas on spot. Always test
Q03 of 03JUNIOR
How do I get started with Kubecost?
ANSWER
Install Kubecost via Helm with a Prometheus backend. It will automatically discover your cluster and show cost allocation. Start by looking at the 'Efficiency' dashboard to identify over-provisioned w
01
What is the difference between Karpenter and Cluster Autoscaler?
JUNIOR
02
Can I use spot instances for stateful workloads?
JUNIOR
03
How do I get started with Kubecost?
JUNIOR
FAQ · 6 QUESTIONS
Frequently Asked Questions
01
What is the difference between Karpenter and Cluster Autoscaler?
Cluster Autoscaler works at the node group level, adding or removing nodes based on pending pods. Karpenter works at the pod level, provisioning the exact instance types needed. Karpenter is faster, more cost-efficient, and supports spot instances natively.
Was this helpful?
02
Can I use spot instances for stateful workloads?
Yes, but only if you have replication, pod disruption budgets, and graceful shutdown handling. Stateful workloads like databases should have leader nodes on on-demand and replicas on spot. Always test with chaos engineering.
Was this helpful?
03
How do I get started with Kubecost?
Install Kubecost via Helm with a Prometheus backend. It will automatically discover your cluster and show cost allocation. Start by looking at the 'Efficiency' dashboard to identify over-provisioned workloads.
Was this helpful?
04
What is the typical savings from using Karpenter with spot?
Typical savings range from 50% to 70% compared to on-demand only. The exact amount depends on your workload profile and spot instance availability. Stateless batch jobs see the highest savings.
Was this helpful?
05
How do I prevent spot interruptions from causing downtime?
Use pod disruption budgets (PDBs) with maxUnavailable set to 1 or 2, implement preStop hooks for graceful shutdown, and spread pods across multiple availability zones. Also use Karpenter's spot-to-spot consolidation to move pods before interruption.
Was this helpful?
06
Is Kubecost free?
Kubecost has a free open-source version with core features. The paid version adds multi-cluster support, advanced reporting, and alerting. For most teams, the free version is sufficient.