Resource Efficiency with Bin Packing in Kubernetes

Learn how bin packing in Kubernetes optimizes resource utilization in large clusters, reducing costs and improving performance with strategies like MostAllocated and RequestedToCapacityRatio.

Resource Efficiency with Bin Packing in Kubernetes

Kubernetes is the leading platform for orchestrating containerized workloads. It helps organizations run large-scale applications with high availability and scalability. But clusters can grow to thousands of nodes. At that size, efficient resource use matters. It cuts costs and reduces environmental impact while keeping performance steady.

Bin packing helps here. It is a combinatorial optimization technique. It places pods — Kubernetes' smallest deployable units — onto nodes with care. The goal is to maximize resource usage and reduce the number of nodes required. This article covers how bin packing works in Kubernetes, its benefits, its challenges, and a practical example from large clusters.

Understanding Bin Packing in Kubernetes

Bin packing comes from computer science. The goal is simple: pack items of different sizes into as few containers as possible, with little waste. In Kubernetes, pods are the "items" and nodes are the "bins." Resources like CPU, memory, and extended resources (such as GPUs) define their "sizes." The Kubernetes scheduler uses bin packing strategies to place pods on nodes. This makes good use of compute resources while still respecting constraints like pod affinity, taints, and resource limits.

The scheduler's NodeResourcesFit plugin supports two main bin packing strategies:

  • MostAllocated: Scores nodes based on resource utilization. It favors nodes with higher allocation, so pods pack tightly.
  • RequestedToCapacityRatio: Scores nodes with a customizable function of the request-to-capacity ratio. You can fine-tune the weighting for resources, including extended ones like GPUs.

These strategies are the opposite of spreading workloads across many nodes. Spreading can leave nodes underutilized and raise costs, especially in cloud environments like AWS EKS.

Benefits of Bin Packing

Bin packing helps Kubernetes clusters in several ways:

  • Cost Reduction: Packing pods onto fewer nodes lets you shrink the cluster. That cuts infrastructure costs. AWS reports up to 66% savings when bin packing is combined with tools like Karpenter or Cluster Autoscaler.
  • Resource Utilization: Efficient packing wastes less CPU and memory. Nodes then run near full capacity.
  • Performance: Tight packing matches pod needs to node capacity. This reduces resource contention and keeps workloads stable.
  • Environmental Impact: Fewer nodes mean less power use and lower carbon emissions. This supports greener operations.
  • Scalability: Bin packing lets large clusters handle changing workloads without overprovisioning. Kubernetes v1.21 supports up to 5,000 nodes.

Challenges and Trade-offs

Bin packing is powerful, but it brings real challenges:

  • Complexity: Placing pods to optimize CPU, memory, and GPUs across thousands of pods is NP-hard. Schedulers must use heuristic algorithms, which may not find the best solution.
  • Constraints: Pod Disruption Budgets (PDBs), anti-affinity rules, and taints can limit where pods go. This reduces packing efficiency. For example, PDBs keep pods available. But they may block evictions, leaving nodes underutilized.
  • Overpacking Risks: Cramming too much onto a node can hurt performance. If resource spikes hit, nodes may crash. Setting accurate requests and limits is critical to avoid this.
  • Dynamic Workloads: In large clusters, workloads shift over time. You need continuous monitoring and adjustment to stay efficient. Tools like Vertical Pod Autoscaler (VPA) help by recommending resource adjustments.
  • Scheduler Overhead: Custom bin packing configs — especially for extended resources — add complexity to the scheduler. In massive clusters, this can slow down pod placement.

To manage these risks, cluster admins should balance bin packing with topology spread constraints, watch resource usage closely, and use automation tools.

Bin Packing Strategies in Action

The Kubernetes scheduler’s NodeResourcesFit plugin supports bin packing through its scoring strategies. Let’s explore each:

MostAllocated Strategy

This strategy prioritizes nodes with the highest resource utilization, encouraging tight packing. For each resource (e.g., CPU, memory), admins can assign weights to influence scoring. For example, a node using 80% of its CPU and 90% of its memory scores higher than one using 50% of both, assuming equal weights. This is ideal for clusters where maximizing node usage is the primary goal.

RequestedToCapacityRatio Strategy

This strategy is more flexible. It scores nodes with a function of their request-to-capacity ratio. Admins can tune that function. They can favor high utilization (bin packing) or low utilization (spreading). They can also assign weights to resources, including extended ones like intel.com/foo (e.g., custom hardware). For instance, a configuration might prioritize GPUs over CPU for AI workloads. This ensures scarce resources are fully utilized.

Both strategies are configured via the KubeSchedulerConfiguration file. You pass this file to the scheduler with the --config flag. Automation tools like Karpenter or third-party solutions like CAST AI enhance these strategies. They dynamically adjust node types and evict pods to optimize packing.

Example: Bin Packing in a Large Cluster

Consider a large Kubernetes cluster running on AWS EKS with 2,000 nodes, hosting a mix of web services and machine learning workloads. The cluster has heterogeneous nodes: some with high CPU (e.g., c5.4xlarge), others with GPUs (e.g., g4dn.xlarge). The goal is to optimize resource utilization for cost savings while ensuring performance.

Cluster Setup

  • Nodes: The cluster has 1,500 CPU-optimized nodes. Each has 16 vCPUs and 32Gi of memory. It also has 500 GPU nodes with 4 GPUs, 8 vCPUs, and 16Gi of memory each.
  • Workloads: The cluster runs 50,000 pods. Of these, 40,000 are web service pods. Each requests 0.5 vCPU and 1Gi of memory. The other 10,000 are ML pods. Each requests 1 GPU, 2 vCPUs, and 4Gi of memory.
  • Constraints: Web pods use topology spread for fault tolerance. This keeps them distributed across availability zones. ML pods must run on GPU nodes. They also have anti-affinity rules to avoid resource contention.

Bin Packing Configuration

To turn on bin packing, the cluster admin sets the scheduler to use the RequestedToCapacityRatio strategy. The goal is to favor GPU use for ML pods, and CPU and memory use for web pods. The configuration looks like this:

apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
  - pluginConfig:
      - name: NodeResourcesFit
        args:
          scoringStrategy:
            type: RequestedToCapacityRatio
            resources:
              - name: nvidia.com/gpu
                weight: 5
              - name: cpu
                weight: 3
              - name: memory
                weight: 1
            requestedToCapacityRatio:
              shape:
                - utilization: 0
                  score: 0
                - utilization: 100
                  score: 10

This setup scores nodes higher when they are more utilized. The score is 0 at 0% use and 10 at 100% use. GPUs carry the most weight because they are scarce. CPU comes next, then memory. The scheduler is updated with --config=/path/to/config.yaml.

Execution

  1. ML Pods: The scheduler places ML pods on GPU nodes. It favors nodes with high GPU use that still have free capacity. For example, a node with 3/4 GPUs used scores higher than one with 1/4 used. GPUs get filled before work spreads to new nodes.
  2. Web Pods: Web pods are packed onto CPU-optimized nodes. Topology spread constraints are still respected. The scheduler favors nodes with high CPU and memory usage, fitting many pods per node to cut waste.
  3. Autoscaling: Karpenter watches the cluster. It adds new nodes only when no existing node can fit a pending pod. It also removes underused nodes, moving pods off through eviction to keep packing tight.
  4. Monitoring: Tools like Prometheus track node utilization. They alert admins to nodes that are underpacked or facing resource contention. VPA suggests resource fixes for pods with wrong requests.

Outcome

  • Before Bin Packing: Pods were spread across 1,800 nodes, with many underutilized (average 60% CPU, 50% memory, 70% GPU usage). The cluster cost was high due to idle resources.
  • After Bin Packing: Pods are consolidated onto 1,400 nodes, with average utilization at 85% CPU, 80% memory, and 95% GPU. Karpenter terminates 400 nodes, saving ~22% on EC2 costs. Performance remains stable, with no significant latency spikes.
  • Environmental Impact: Reduced node count lowers power consumption, aligning with sustainability goals.

This example demonstrates how bin packing, combined with automation and monitoring, optimizes large clusters for cost, performance, and sustainability.

Best Practices for Bin Packing

To get the most out of bin packing:

  • Set Accurate Resource Requests/Limits: Pods with no requests, or with inflated limits, hurt packing. Rightsize your workloads. Use VPA or historical data to do this.
  • Monitor Continuously: Use Prometheus or Grafana to see utilization. Look for waste. Adjust configurations as workloads change.
  • Leverage Automation: Tools like Karpenter, Cluster Autoscaler, or CAST AI's Evictor automate node scaling and pod consolidation. This cuts manual effort.
  • Balance Constraints: Keep anti-affinity rules and PDBs to a minimum. This allows tighter packing. But use topology spread to keep availability.
  • Test Configurations: Large clusters need testing. Test scheduler configurations in staging first. This avoids performance impacts. On managed clusters like EKS, default policies are immutable. Use custom schedulers.

The Bottom Line

Bin packing is a cornerstone of resource efficiency in Kubernetes. It helps organizations run large clusters at lower cost, with good performance and less waste. Strategies like MostAllocated and RequestedToCapacityRatio help here. So do tools like Karpenter and VPA. With them, admins can place pods tightly while handling constraints and dynamic workloads.

The example of a 2,000-node EKS cluster shows the real-world impact. Bin packing cut the node count and costs without hurting reliability.

Kubernetes adoption keeps growing. Mastering bin packing will stay essential for running scalable, cost-effective cloud-native environments.