Cloud cost, Kubernetes
Cloud Cost Optimization Is Not Always About Reducing Resources
Smaller VMs, fewer replicas and deleted resources are the obvious levers. Sometimes they make the total bill go up.
When a cloud bill gets attention, the first round of changes is usually predictable. Smaller machine types. Fewer replicas. A sweep for unattached disks and forgotten test environments. Some of that is worth doing, and the cleanup part almost always is.
The trouble starts when cost optimization turns into resource reduction. A downsized node pool can end up with more nodes. Lower CPU requests can make an autoscaler add replicas. Moving a workload to a cheaper region can add a transfer bill bigger than the compute it saved. Making things smaller is one tool, and it is easy to use it where it does not fit.
The argument here is simple: the unit price of a resource matters less than how much of it you actually use, and what it costs to run everything around it. Sometimes the right move is a bigger machine, a shared cluster or a higher request. The rest of this article works through when that is true, and when it is not.
Bigger instances can be cheaper
Within a general-purpose machine family, a 16 vCPU VM usually costs about four times as much as a 4 vCPU VM. Per vCPU, the price is the same. So the saving from larger instances never comes from the list price. It comes from how much of each machine your workloads can actually use.
Where the capacity goes
On a Kubernetes node, not all of the machine is available to your pods. Some of it is reserved before scheduling starts, and some is taken by workloads that run on every node:
- System reservations for the kubelet, the container runtime and the operating system, plus a memory buffer for eviction. Kubernetes subtracts these from the node's capacity to get its allocatable resources. Managed providers calculate the reservation from the node size, and on most of them it is a smaller share of a bigger node.
- DaemonSets: log shipping, metrics agents, the CNI plugin, kube-proxy, CSI drivers, security agents. Each runs one copy per node, so its cost scales with node count, not with your workload.
- Fragmentation: capacity left on a node that is too small for the next pod. A node with 0.5 vCPU free cannot run a pod that requests 1.5 vCPU, so that 0.5 vCPU is paid for and idle.
You can see the first two directly on any node:
kubectl describe node <node-name> | grep -A 6 -E "^(Capacity|Allocatable):" kubectl describe node <node-name> | grep -A 8 "Allocated resources"
Some costs that scale with node count are not in the compute bill at all. Several monitoring and security products price per host. Datadog's infrastructure monitoring, for example, is billed per host, so twenty small nodes cost more to monitor than four large ones running the same pods.
A worked example
Take 40 replicas of a service, each requesting 1.5 vCPU and 3 GiB of memory, and compare two node pools. Assume the provider reserves about 0.1 vCPU on the small node and 0.2 vCPU on the large one, and that DaemonSets request 0.4 vCPU per node. Memory is not the constraint in either case.
| Illustrative | Small nodes | Large nodes |
|---|---|---|
| Node shape | 4 vCPU, 16 GiB | 16 vCPU, 64 GiB |
| Price per node | $100 / month | $400 / month |
| CPU left for pods | 3.5 vCPU | 15.4 vCPU |
| Pods per node | 2 | 10 |
| Nodes for 40 pods | 20 | 4 |
| Monthly compute | $2,000 | $1,600 |
| CPU spent on DaemonSets | 8 vCPU | 1.6 vCPU |
| With one spare node | 21 nodes, $2,100 | 5 nodes, $2,000 |
4 vCPU node, 3.5 vCPU left for pods [ pod 1.5 ][ pod 1.5 ][ 0.5 idle ] 16 vCPU node, 15.4 vCPU left for pods [1.5][1.5][1.5][1.5][1.5][1.5][1.5][1.5][1.5][1.5][ 0.4 idle ]
The large pool is 20% cheaper for the same 40 pods. The pods did not get smaller and no list price changed. The difference is 0.5 vCPU stranded on each of twenty small nodes, plus sixteen extra copies of every DaemonSet.
The last row matters too. To survive the loss of one node without pods going Pending, you need a spare. A spare small node costs $100. A spare large node costs $400, which narrows the gap to $100. With fewer, larger nodes, each node is a bigger share of your capacity, and so is the headroom you keep for failure.
When larger nodes are the wrong call
- Blast radius. A node failure, kernel upgrade or drain takes out more pods at once. Pod disruption budgets and topology spread constraints help, but only if there are enough nodes to spread across.
- Zone spread. With four nodes across three zones, one zone holds half the capacity. Losing that zone hurts far more than losing one zone of an evenly spread pool of twenty.
- Scaling granularity. The cluster autoscaler adds and removes whole nodes. If load moves by a few pods at a time, large nodes mean paying for capacity in large steps.
- Pod density limits. Providers cap the number of pods per node, and the cap depends on the network mode. Many small pods on a large node can hit the pod limit before they use the CPU.
- Mixed workload shapes. If most pods are small and a few are very large, one node shape rarely fits both. Separate node pools, or node auto-provisioning on GKE, usually do better than one size for everything.
The case for larger nodes is strongest when there are still enough of them to spread across zones, and when typical pod sizes are a reasonable fraction of the node. With only a handful of nodes per pool, the headroom you need for failures tends to eat the saving.
Consolidating Kubernetes clusters
Clusters multiply easily. One per environment, one for a team that wanted its own, one for a tool that was supposed to be temporary. Each makes sense when it is created. Together they carry a fixed cost that has little to do with the workloads inside them.
The fixed cost of a cluster
Every cluster pays for some things however busy it is:
- A control plane management fee on many managed services, depending on the tier. Some providers waive it for one cluster or offer a free tier without an uptime SLA.
- A minimum node count, usually spread across zones for availability, even when the workloads would fit on one node.
- System workloads: DNS, metrics-server, ingress controllers, cert-manager, policy engines, monitoring and logging agents. All of them run again in every cluster.
- Networking: a NAT gateway (Cloud NAT on GCP, NAT Gateway on Azure) with an hourly charge plus per-GB processing, and load balancers for ingress, each billed by the hour.
- Observability: per-host agents, plus log ingestion from system components that produce logs whether or not anything else is running.
- People's time: upgrades, add-on versions, certificates and access policies. This rarely shows up in the bill and often costs the most.
A worked example
Imagine four GKE or AKS clusters: production with six nodes, and staging, development and an internal tools cluster with three nodes each. The three non-production clusters run at low utilisation most of the day. The proposal is to leave production alone and move the other three into one non-production cluster, separated by namespace.
Before: 4 clusters, 15 nodes
prod 6 nodes fee + NAT + LB + agents
staging 3 nodes fee + NAT + LB + agents
dev 3 nodes fee + NAT + LB + agents
tools 3 nodes fee + NAT + LB + agents
After: 2 clusters, 10 nodes
prod 6 nodes fee + NAT + LB + agents
non-prod 4 nodes fee + NAT + LB + agents
namespaces: staging, dev, tools| Monthly, illustrative | Before | After |
|---|---|---|
| Nodes, 4 vCPU at $100 each | 15 nodes, $1,500 | 10 nodes, $1,000 |
| Management fee, $70 per cluster | $280 | $140 |
| NAT gateway, $45 per cluster before data | $180 | $90 |
| Ingress load balancer, $20 per cluster | $80 | $40 |
| Per-host monitoring, $15 per node | $225 | $150 |
| Total | $2,265 | $1,420 |
That is about $845 a month, or 37%. The three non-production clusters were each held at three nodes by availability rules, not by load, so merging them removes five nodes. The rest is fixed per-cluster cost that disappears with the clusters.
The work is not free. Each namespace needs its own resource quota, network policies and RBAC, and the merged cluster needs room for all three environments to be busy at the same time. A quota per namespace looks like this:
apiVersion: v1
kind: ResourceQuota
metadata:
name: compute
namespace: staging
spec:
hard:
requests.cpu: "6"
requests.memory: 24Gi
limits.memory: 32GiOnce a quota covers CPU and memory, pods without requests and limits are rejected in that namespace, so pair it with a LimitRange that sets defaults.
What you give up
Consolidation trades fixed cost for shared fate. A cluster upgrade, a broken admission webhook or a misconfigured CNI now affects staging, development and tools at once. A noisy batch job in development can starve staging if quotas and priorities are loose. Some isolation requirements cannot be met with namespaces at all: compliance scopes, separate cloud accounts or subscriptions, or tenants who must not share a kernel.
That is why production stays separate in this example. The question is not how few clusters you can run. It is which boundaries your workloads need, and whether a namespace is a strong enough boundary for each of them.
Right-sizing is more than downsizing
Right-sizing means matching allocations to what workloads need. Sometimes that means smaller. Sometimes it means larger, or the same total with a different shape. Doing it well depends on keeping three numbers apart.
Requests, limits and usage
- Requests are what the scheduler reserves. They decide how many pods fit on a node, and so how many nodes you pay for. Usage below the request is capacity you pay for and do not use.
- Limits are a ceiling. A container that reaches its CPU limit is throttled by the kernel's CFS quota. A container that goes over its memory limit is OOMKilled.
- Usage is what the container actually consumes, and it changes over the day, the week and the release cycle.
Requests drive cost. Limits drive failure modes. Usage is the evidence for setting both.
The average is the wrong number
CPU usage averaged over a week hides the peaks that matter. A service that averages 0.2 vCPU might need 1.2 vCPU for a few minutes every hour, during a cache refresh, a report export or a burst of traffic. Memory is less forgiving still: too little CPU makes things slow, too little memory kills the container.
Size CPU requests from a high percentile of usage over a window that includes your real peaks (a week at minimum, longer if you have monthly cycles), and memory limits from the highest usage you have seen, plus a margin. In Prometheus, with cAdvisor and kube-state-metrics:
# CPU used as a share of CPU requested, per namespace
sum by (namespace) (rate(container_cpu_usage_seconds_total{container!=""}[5m]))
/
sum by (namespace) (kube_pod_container_resource_requests{resource="cpu"})
# 95th percentile CPU per container over 7 days
quantile_over_time(0.95,
rate(container_cpu_usage_seconds_total{container!=""}[5m])[7d:5m]
)
# Peak memory working set per container over 7 days
max_over_time(container_memory_working_set_bytes{container!=""}[7d])
# Share of CPU periods in which each container was throttled
sum by (namespace, pod, container) (rate(container_cpu_cfs_throttled_periods_total[5m]))
/
sum by (namespace, pod, container) (rate(container_cpu_cfs_periods_total[5m]))Cloud Monitoring for GKE and Datadog's Kubernetes views show the same request-versus-usage comparison without writing queries. The Vertical Pod Autoscaler in recommendation mode computes suggested requests from history without changing anything:
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: api
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: api
updatePolicy:
updateMode: "Off"What blind downsizing looks like
Take a hypothetical API service with ten replicas. Each requests 1 vCPU and 2 GiB, with a 2 vCPU CPU limit and a 2 GiB memory limit. Average CPU is 0.2 vCPU per pod, the 95th percentile is about 0.45, and short peaks reach 1.2. Memory sits around 0.8 GiB and climbs to 1.3 GiB during exports. A cost review sees 80% of the CPU request unused and cuts everything to match the average.
| Per pod | Before | Cut to average | Sized to behaviour |
|---|---|---|---|
| CPU request | 1 vCPU | 0.25 vCPU | 0.5 vCPU |
| CPU limit | 2 vCPU | 0.5 vCPU | 1.5 vCPU |
| Memory request | 2 GiB | 1 GiB | 1.5 GiB |
| Memory limit | 2 GiB | 1 GiB | 1.5 GiB |
The middle column saves the most on paper and fails in three ways:
- At peaks each pod wants 1.2 vCPU and is capped at 0.5. The kernel throttles it, and latency climbs while the CPU graph looks flat, because a throttled container cannot use more than its limit.
- Exports push memory to 1.3 GiB against a 1 GiB limit, so pods are OOMKilled in the middle of requests.
- The Horizontal Pod Autoscaler measures CPU utilisation as a percentage of the request. With a 70% target, the old request meant scaling out at 0.7 vCPU per pod. The new one means scaling out at 0.175 vCPU, which is below the average. The autoscaler now runs extra replicas all day, and part of the saving goes with them.
The last column halves the CPU request, still costs less than the original, and survives its own peaks. Getting there needed the percentile, the peak and an understanding of how the autoscaler reads requests, not a single average. Whether to set CPU limits at all is a fair debate, and many teams leave them off latency-sensitive services. A limit below the real peak, though, guarantees throttling.
Look at the whole bill
Compute is usually the largest line, which is why it gets the attention. It is rarely the only line that moves when the architecture changes.
| Cost | What drives it |
|---|---|
| Compute | Requested capacity, node shape, pricing model (on-demand, committed, spot) |
| Storage | Provisioned size and class, snapshots, unattached volumes |
| Network egress | Traffic leaving a zone, a region or the provider |
| NAT | Gateway hours plus every GB processed |
| Load balancers | Hourly charge per load balancer or rule, plus data |
| Monitoring and logging | Hosts, custom metrics, log volume ingested and retained |
| Managed services | Databases, caches and queues, often sized separately from the cluster |
| Inter-region traffic | Replication, cross-region calls, data stored far from compute |
When compute savings move to the network
Say a batch workload runs in its own cluster in region A, next to the storage bucket it reads from. It gets consolidated into a larger cluster in region B, which saves an illustrative $300 a month in compute and fixed cluster cost. The job still reads about 20 TB a month from the bucket in region A.
Before batch cluster (region A) ──► bucket (region A) same-region reads After shared cluster (region B) ──► bucket (region A) inter-region transfer, billed per GB
At an illustrative inter-region price of $0.02 per GB, 20 TB is about $400 a month. The change costs $100 more than it saves, and every job runs slower because its data is further away. If that traffic leaves through a NAT gateway rather than a private path, NAT processing is charged on top. On GCP, Private Google Access keeps traffic to Google APIs off Cloud NAT. On Azure, private endpoints do the same for storage accounts.
Smaller versions of this happen inside a single region. Spreading chatty services across zones for availability adds cross-zone transfer on providers that bill it. Before calling a change a saving, estimate what it does to every line that depends on it, not only the one you set out to reduce.
Consolidation versus isolation
Most of the choices above come down to one trade-off. Shared infrastructure is cheaper to run. Isolated infrastructure fails more independently. Neither is right by default.
| Concern | Shared | Isolated |
|---|---|---|
| Cost | Fixed costs paid once, better bin packing | Fixed costs paid per cluster, account or pool |
| Environment separation | Namespaces, quotas and policies | Separate clusters, projects or subscriptions |
| Security boundary | Shared control plane and nodes, unless node pools or sandboxing separate them | Separate credentials, networks and control planes |
| Resource contention | Needs quotas, priority classes and limits | Contained by design |
| Fault isolation | An upgrade or bad add-on affects everyone | Failures stay in one environment |
| Operations | Fewer things to upgrade and monitor | More upgrades, each smaller and lower risk |
In a multi-tenant cluster the hard part is rarely the first tenant. It is the fifth, when quotas, network policies, priority classes, admission policies and on-call ownership all have to be right at the same time. Without the time to maintain those controls, the cheaper architecture can cost more in incidents than it saved in fees.
A pattern that often works: share aggressively in non-production, keep production separate, and isolate anything with a compliance or tenant boundary at the account or subscription level, where billing and access are separated as well.
A method that holds up
Cost work goes better when it is treated like any other engineering change: measured before, made in small steps, and measured after.
- Understand current spend. Export billing data somewhere you can query it: the Cloud Billing export to BigQuery on GCP, or Cost Management exports on Azure. Turn on GKE cost allocation, or run OpenCost, to split cluster cost by namespace and label.
- Find the biggest contributors. Sort by service and SKU. A handful of lines usually make up most of the bill, and that is where the effort belongs.
- Measure actual utilisation. Compare requests with usage per namespace and per workload over at least a week, using Prometheus, Cloud Monitoring or Datadog.
- Identify underused infrastructure. Clusters, node pools and databases with low utilisation, and resources nobody owns.
- Evaluate alternatives. Other node shapes, consolidation, autoscaler settings, spot capacity for interruptible work, committed-use discounts or reservations for steady load. Buy commitments after right-sizing, not before, or you commit to the waste.
- Estimate savings and added costs. Include network, NAT, monitoring and engineering time. For Terraform changes, Infracost shows the monthly cost difference of a plan before it is applied.
- Weigh reliability. Check what the change does to headroom, failure domains, latency and recovery time.
- Change incrementally. One node pool, namespace or environment at a time, with a way back.
- Monitor the result. Watch throttling, OOMKills, pending pods, latency and the bill itself for a full billing cycle.
- Review regularly. Workloads change, and last quarter's right size drifts.
For the second step on GCP, this query against the billing export lists the largest cost lines for the last 30 days, net of credits:
SELECT
service.description AS service_name,
sku.description AS sku_name,
ROUND(SUM(cost) + SUM(IFNULL(
(SELECT SUM(c.amount) FROM UNNEST(credits) AS c), 0)), 2) AS net_cost
FROM `my-project.billing.gcp_billing_export_v1_XXXXXX`
WHERE usage_start_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
GROUP BY 1, 2
ORDER BY net_cost DESC
LIMIT 20And for the sixth, comparing a Terraform branch against main:
# On main infracost breakdown --path . --format json --out-file infracost-base.json # On the branch with the change infracost diff --path . --compare-to infracost-base.json
Key takeaways
- Cost optimization is an engineering problem. The bill tells you where to look, and utilisation tells you what to change.
- Utilisation matters more than resource count. Fewer, larger nodes can cost less because less capacity is stranded, not because they are cheaper per vCPU.
- Every cluster has a fixed cost. Consolidate where the isolation is not needed, and keep the boundary where it is.
- Requests drive cost and limits drive failure. Size them from percentiles and peaks, not averages.
- Changes move cost between lines. Check network, NAT, monitoring and managed services before calling something a saving.
- Measure before and after, change one thing at a time, and keep reviewing.
Conclusion
The point of cost work is to stop paying for capacity and overhead you do not use, without making the system slower or more fragile. Sometimes that means smaller instances. Often enough it means larger nodes, fewer clusters, a higher request in one place so that others can come down, or leaving something alone because the saving is not worth the risk.
The useful habit is to ask what a change does to the total, across every cost line and across the time people spend running it. If a cheaper setup needs more nodes, more incidents or more engineering hours, it was not cheaper.