25 minute read
As organizations embrace Kubernetes for managing containerized applications at scale, the underlying infrastructure costs, particularly for compute resources, become a critical factor. Gardener, the open-source Kubernetes management platform, empowers organizations like SAP, STACKIT, T-Systems, and others (see adopters) to operate tens of thousands of Kubernetes clusters efficiently across diverse environments. Gardener’s role as a core technology in initiatives like NeoNephos, aimed at advancing digital autonomy in Europe (see KubeCon London 2025 Keynote and press announcement), further underscores the need for cost-effective and sustainable operations.
At the heart of Gardener’s architecture is the concept of “Kubeception” (see readme and architecture): Gardener runs on Kubernetes (called a runtime cluster), facilitates access through a self-managed node-less Kubernetes cluster (called the garden cluster), manages Kubernetes control planes as pods within self-managed Kubernetes clusters that provide high scalability to Gardener (called seed clusters), and provisions end-user Kubernetes clusters (called shoot clusters). Therefore, optimizing Gardener’s own Kubernetes-related resource consumption directly translates into cost savings across all these layers, benefiting both Gardener service providers and the end-users consuming the managed clusters.
While infrastructure costs span compute, storage, and networking, compute resources (the virtual machines running Kubernetes nodes) typically represent the largest share of the bill. Over the past years, the Gardener team has undertaken a significant effort to optimize these costs. This blog post details our journey, focusing heavily on the compute optimizations that go beyond standard autoscaling practices, ultimately delivering substantial savings that benefit the entire Gardener ecosystem.
We’ll build upon the foundations laid out in our Pod Autoscaling Best Practices Guide. You may want to check it out beforehand, as we’ll only touch upon a few key recommendations from it in this blog post, not delving into the full depth required for effective pod autoscaling – a prerequisite for the compute optimizations discussed here.
You can’t optimize what you can’t measure. Our first step was to gain deep visibility into our spending patterns. We leveraged:
Cloud providers offer significant discounts for commitment: Reserved Instances (RIs) on AWS/Azure, Savings Plans (SPs) on AWS/Azure, and Committed Use Discounts (CUDs) on GCP. However, maximizing their benefit requires careful planning, which is not the primary subject of this blog post. Companies typically have tools that generate recommendations from cost reports, suggesting the purchase of new RIs, SPs, or CUDs if on-demand usage consistently increases. Two key learnings emerged in this context, though:
We also actively looked for waste, specifically orphaned resources. Development and experimentation inevitably lead to forgotten resources (virtual machines, disks, load balancers, etc.). We implemented processes like requiring all resources to include a personal identifier in the name or as a label/tag to facilitate later cleanup. Initially, we generated simple reports, but it became clear that this task required a more professional approach. Unaccounted-for resources aren’t just costly; they can also pose security risks or indicate security incidents. Therefore, we developed the gardener/inventory
tool. This tool understands Gardener installations and cross-references expected cloud provider resources (based on Gardener’s desired state and implementation) against actually existing resources. It acts as an additional safety net, alerting on discrepancies (e.g., unexpected load balancers for a seed, unmanaged virtual machines in a VPC) which could indicate either cost leakage or a potential security issue, complementing Gardener’s existing security measures like high-frequency credentials rotation, image signing and admission, network policies, Falco, etc.
If possible, avoid operating too many small seeds unless required by regulations or driven by end-user demand. As Gardener supports control plane migration, you can consolidate your control planes into fewer, larger seeds where reasonable. Since starting Gardener in production in 2017, we’ve encountered technological advancements (e.g., Azure Availability Sets to Zones) and corrected initial misconfigurations (e.g., too-small CIDR ranges limiting pod/node counts) that necessitated recreating seeds. While hard conflicts (like seed/shoot cluster IP address overlaps) can sometimes block migration to differently configured seeds, you can often at least merge multiple seeds into one or fewer. The key takeaway is that a less fragmented seed landscape generally leads to better efficiency.
However, there is a critical caveat: Gardener allows control planes to reside in different regions (or even different cloud providers) than their worker nodes. This flexibility comes at the cost of inter-regional or internet network traffic. These additional network-related costs can easily negate efficiency gains from seed consolidation. Therefore, consolidate thoughtfully, being mindful that excessive consolidation across regions can significantly increase network costs (intra-region traffic is cheaper than inter-region traffic, and internet traffic is usually the most expensive).
While compute was our main focus, we also addressed significant cost drivers in networking and storage early on.
exec
into pods, etc.). This proliferation of LBs was expensive. We transitioned to a model using a central Istio ingress-gateway per seed cluster with a single LB, leveraging SNI (Server Name Indication) routing to direct traffic to the correct control plane API servers. We also reversed the connection direction: shoots now connect to seed clusters, and seeds connect to the garden cluster. This reduced the need for LBs exposing seed components and enabled private shoots or even private seeds behind firewalls.watch
requests rather than frequent list
requests to minimize API server load and improve responsiveness. Leveraging server-side filtering via label selectors and field selectors reduces the amount of data transferred.Storage costs were addressed by being mindful of Persistent Volume Claim (PVC) size and performance tiers (e.g., standard HDD vs. premium SSD). Choosing the right storage class based on actual workload needs prevents overspending on unused capacity or unnecessary IOPS.
This is where the most significant savings were realized. Optimizing compute utilization in Kubernetes is a multi-faceted challenge involving the interplay of several components.
We think of utilization optimization in two stages:
You need to optimize both stages for maximum efficiency.
LeastAllocated
strategy). For cost optimization, packing pods tightly onto fewer nodes (using the MostAllocated
strategy, often called bin-packing) is more effective. Gardener runs Kubernetes control planes as pods on seed clusters. Switching the Kube-Scheduler profile in our seed clusters to prioritize bin-packing yielded over 20% reduction in machine costs for these clusters simply by requiring fewer nodes. We also made this scheduling profile available for shoot clusters (see Gardener PR #6251).--node-cidr-mask-size
(e.g., /22
for ~1024 IPs, though assume ~80% effective due to IP reuse; see kube-controller-manager docs) to allocate sufficient IPs per node.--kube-reserved
resources (see kubelet docs) to account for system overhead.--max-pods
value (again, see kubelet docs) to inform the kubelet and scheduler of the node’s actual pod capacity.The cluster autoscaler (CA) adds or removes nodes based on pending pods and node utilization. We tuned its behavior for better cost efficiency:
--scale-down-unneeded-time=15m
: Time a node must be underutilized before CA considers it for removal, allowing removal of persistently unneeded capacity.--scale-down-delay-after-add=30m
: Prevents CA from removing a node too soon after adding one, reducing potential node thrashing during fluctuating load.--scale-down-utilization-threshold=0.9
: We significantly increased this threshold (default is 0.5). It instructs CA to attempt removing any node running below 90% utilization if it can safely reschedule the existing pods onto other available nodes; otherwise, it does nothing. We have run with this setting successfully for a long time, supported by properly tuned pod priorities, PDBs managing voluntary disruptions, highly available control planes, and Kubernetes’ level-triggered, asynchronous nature.Right-sizing pods dynamically is key. Kubernetes offers HPA and VPA:
target.type: AverageValue
) rather than utilization percentage (target.type: Utilization
). This prevents conflicts where VPA changes the requests, which would otherwise immediately invalidate HPA’s utilization calculation.spec:
minReplicas: 3
maxReplicas: 12
metrics:
- resource:
name: cpu
target:
averageValue: 6 # Target 6 cores average usage per pod (Note: String value often required)
type: AverageValue
type: Resource
- resource:
name: memory
target:
averageValue: 24Gi # Target 24Gi average usage per pod
type: AverageValue
type: Resource
behavior: # Fine-tune scaling behavior
scaleDown:
policies:
- periodSeconds: 300
type: Pods
value: 1
selectPolicy: Max
stabilizationWindowSeconds: 1800
scaleUp:
policies:
- periodSeconds: 60
type: Percent
value: 100
selectPolicy: Max
stabilizationWindowSeconds: 60
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: kube-apiserver
--target-cpu-percentile
/ --target-memory-percentile
(determining the percentile of historical usage data to include in target recommendations, ignoring spikes above) and margin/bound parameters to make VPA less sensitive to tiny spikes and react faster and more accurately to sustained changes.--cpu-histogram-decay-half-life
(from 24h to 15m) and --recommendation-lower-bound-cpu-percentile
(from 0.5 to 0.7) to follow changes in CPU utilization more closely (work on memory is ongoing).minAllowed
: We set minAllowed
(per VPA resource) based on observed usage patterns and historical outage data related to VPA scaling down too aggressively.maxAllowed
: We set maxAllowed
(per VPA controller) to prevent request recommendations from exceeding node capacity. We found maxAllowed
couldn’t be configured centrally in the VPA controller, so we contributed this feature upstream (see Kubernetes Autoscaler Issue #7147 and corresponding PR).Burstable
QoS class (requests set, ideally no limits) for most workloads. Avoid BestEffort
(no requests/limits), as these pods are the first to be evicted under pressure. Avoid Guaranteed
(requests match limits), as limits often cause more harm than good. See our Pod Autoscaling Best Practices Guide. Pods in the Guaranteed
QoS class, or generally those with limits, will be actively CPU-throttled and can be OOMKilled even if the node has ample spare capacity. Worse, if containers in the pod are under VPA, their CPU requests/limits often won’t scale up appropriately because CPU throttling goes unnoticed by VPA.Before optimizing machine type selection, we established comprehensive machine utilization monitoring. This was important during individual improvement steps to validate their effectiveness. We collect key metrics per Gardener installation, cloud provider, seed, and worker pool, and created dashboards to visualize and monitor our machine costs. These dashboards include:
Selecting the right machine type is critical for cost efficiency. Several factors come into play:
While mixing diverse workloads seems efficient at first glance, dedicated node pools for specific workload types proved beneficial for several reasons:
safe-to-evict: false
: Some pods (like single-replica stateful components for non-HA clusters) cannot be safely evicted by the Cluster Autoscaler. Mixing these with evictable pods on the same node can prevent the CA from scaling down that node, even if it’s underutilized, negating cost savings. Placing these non-evictable pods in a dedicated pool (where scale-down might be disabled or carefully managed) isolates this behavior.Early on, we used a guide for operators to estimate a reasonable machine size for a seed cluster based on the number of hosted control planes, e.g.:
Optimal Worker Pool (CPUxMem+Vols) | Very Low Seed Utilization 0 <= |control planes| < 15 | Low Seed Utilization 5 <= |control planes| < 30 | Medium Seed Utilization 10 <= |control planes| < 70 | High Seed Utilization 30 <= |control planes| < 180 | Very High Seed Utilization 120 <= |control planes| < ∞ |
---|---|---|---|---|---|
AWS | m5.large (2x8+26) | r7i.large (2x16+32) | r7i.xlarge (4x32+32) | r7i.2xlarge (8x64+32) | r7i.2xlarge (8x64+32) |
Azure | Standard_D2s_v5 (2x8+4) | Standard_D4s_v5 (4x16+8) | Standard_D8s_v5 (8x32+16) | Standard_D16s_v5 (16x64+32) | Standard_D16s_v5 (16x64+32) |
GCP | n1-standard-2 (2x8+127) | n1-standard-4 (4x15+127) | n1-standard-8 (8x30+127) | n1-standard-16 (16x60+127) | n1-standard-16 (16x60+127) |
This guide also recommended specific instance families. Choosing the right family requires calculating the workload’s aggregate CPU:memory ratio (total requested CPU : total requested memory across similar workloads). For example, 1000 cores and 6000 GB memory yields a 1:6 ratio.
Next, one must calculate the cost per core and per GB for different instance families and determine the break-even CPU:memory ratio – the point where the resource waste of two families is equal. The cluster autoscaler doesn’t perform this cost-aware analysis; it always weights CPU and memory equally (1:1).
To find the optimal family manually, we followed these steps when adding new generations/families:
For instance, if the break-even ratio between standard (1:4) and high-memory (1:8) families is 1:5.7, and your workload runs at 1:6, the high-memory family is likely more cost-effective.
This manual process was tedious, error-prone, and infrequently performed, leading to suboptimal machine types running in many seeds. To address this, we developed an automated pool recommender based on the following principles:
Comprehensive Data Collection: The recommender gathers metrics across the entire Gardener installation for specific seed sets (groups of seeds with similar configurations like provider and region). For every relevant seed, it collects:
/api/v1/nodes/NODENAME/proxy/stats/summary
). This provides actual cgroup-level data on CPU and memory consumption for kubelet, container runtime, system overhead, and individual pods. Especially for memory, this was the only reliable method we found to get accurate working set bytes overall (simply summing pod metrics is inaccurate due to page cache/sharing; see kernel docs for cgroup-v1 and cgroup-v2).Analyzing the Data: Before recommending new types, the recommender calculates key metrics that act as predictors and provide context:
Simulating Workload on Candidate Machines: This is the core recommendation logic:
kube-reserved
: Estimates CPU/memory needed for kubelet/runtime using our measurement-based model, tailored to the candidate’s capacity (more on that later).machine_costs
(Cores * Cost per Core + GBs * Cost per GB
) for the candidate.excess_costs
(waste) per machine due to factors like:Efficiency = (Cost_of_Usable_Resources) / (Base_Machine_Cost + Estimated_Excess_Cost)
This score reflects how cost-effectively the candidate machine type can serve the workload, factoring in estimated waste.Ranking & Selection:
Efficiency / Cost per Core
. Dividing by cost per core helps prioritize newer/cheaper instance generations or those with better RI/SP coverage, while still heavily favoring the calculated efficiency.preferred
and receives the highest CA expander priority. A threshold (e.g., >5% efficiency improvement) prevents switching the preferred type too frequently, avoiding churn (flapping).NoSchedule
taint to allow workload to slowely migrate away from them.This data-driven, simulation-based approach allowed us to abandon guides like above and manual operations and consistently select machine types that offer the best balance of performance and cost for the specific workloads running on our Gardener seeds.
kube-reserved
Beyond Workload-Naive FormulasAs pod packing density increases, accurately accounting for resources needed by the system itself (kubelet, container runtime, OS) becomes critical. Standard cloud provider formulas for kube-reserved
(see kubelet options) are often workload-naive, based only on total node CPU/memory capacity (see summary blog post). They can either over-reserve (wasting resources) or under-reserve (risking node stability). Our experience showed that formulas considering only node capacity and potentially maxPods
were often significantly inaccurate, leading to either waste or instability.
Therefore, instead of relying on static formulas, we adopted a measurement-based approach combined with predictive modeling:
Measure Actual Overhead: We utilize the data already retrieved via the kubelet summary API. By querying this endpoint across thousands of nodes for all our seeds, we collect the actual CPU (usageNanoCores
) and memory (workingSetBytes
) consumed by the kubelet
and runtime
system containers under various conditions (different machine types, workload profiles like ETCD pools, varying pod densities).
Derive Workload-Aware Ratios: We then calculate key ratios that correlate overhead with workload characteristics, specifically pod density:
ratio_1_used_reserved_core_to_pods
: Average number of pods running per actually used reserved core (performance-normalized across machine types).ratio_1_used_reserved_gi_to_pods
: Average number of pods running per actually used reserved GB of memory.These ratios capture how much system overhead is typically generated per pod on average within a specific pool type for a given seed set. We explored other potential predictors (containers, probes) but found pod count to be the most useful predictor with acceptable standard deviation.
Predict Expected kube-reserved
: We use these measured ratios to predict the necessary kube-reserved
for any candidate machine type considered by the Pool Recommender. The model works as follows:
ratio_1_used_reserved_core_to_pods
and ratio_1_used_reserved_gi_to_pods
to estimate the required kube-reserved
CPU and memory, respectively. This tailors the reservation to the candidate’s specific capacity and performance characteristics.Apply Thresholds for Stability: To prevent minor fluctuations in calculated recommendations from causing constant configuration changes (increasing kube-reserved
can trigger pod evictions), we apply thresholds (hysteresis).
This tailored, data-driven approach to kube-reserved
provides better cost optimization and enhanced stability compared to generic, workload-naive formulas.
Note on system-reserved
: You might wonder why we only discussed kube-reserved
and not system-reserved
. Similar to our reasoning against resource limits, configuring system-reserved
can lead to unexpected CPU throttling or OOM kills for critical system processes outside Kubernetes’ direct management. Therefore, Gardener focuses on configuring kube-reserved
and relies on the kubelet’s eviction mechanisms to manage overall node pressure. See also Reserve Compute Resources for System Daemons.
Cost optimization is an ongoing process, not a one-time fix. We’re actively exploring further improvements:
kube-apiserver
, default connection-based load balancing can lead to uneven load distribution that VPA handles poorly (resulting in over-provisioning for some pods, under-provisioning for others). We have implemented request-based load balancing to distribute load more evenly, allowing VPA to set more accurate requests (see related work).Optimizing Kubernetes compute costs at scale is a complex but rewarding endeavor. Our journey with Gardener involved a multi-pronged approach:
kube-reserved
based on actual system usage patterns rather than static formulas.These efforts have yielded substantial cost reductions for operating Gardener itself and, by extension, for all Gardener adopters running managed Kubernetes clusters. We hope sharing our journey provides valuable insights for your own optimization efforts, whether you’re just starting or looking to refine your existing strategies.