Cost Optimization of GenAI Applications on Kubernetes
local graph
Chapter 7 — Cost Optimization of GenAI Applications on Kubernetes
Section titled “Chapter 7 — Cost Optimization of GenAI Applications on Kubernetes”In this chapter, we will cover the key cost components for deploying GenAI applications in the cloud, covering compute, storage, and networking costs. We will then cover options to optimize these costs, such as right-sizing resources to prevent over-provisioning, thinking through efficient storage management, and networking best practices. This chapter will cover monitoring and optimization tools, such as Kubecost, to identify resource utilization patterns and cost-saving opportunities.
In this chapter, we’re going to cover the following main topics:
- Understanding the key cost components
- Cost optimization techniques
Understanding the key cost components
Section titled “Understanding the key cost components”Key cost components while deploying an application in the cloud typically involve compute, storage, and networking costs:
- Compute costs: Compute could be a significant cost driver for GenAI applications because of their resource-intensive nature. Compute costs are based on the instance size, which includes CPU, GPU, and memory sizes. On AWS, these compute instances are billed on a per-second basis, with a minimum of 60 seconds. So, after the first minute, these costs are billed in one-second increments. Refer to AWS pricing documentation at https://aws.amazon.com/ec2/pricing/ for a deeper understanding.
- Storage costs: GenAI models often need large amounts of data for training and inference, so storage is another critical cost component. Key storage costs include object storage and block storage. Object storage, such as Amazon S3, is typically used for storing datasets such as image, text, or video files. The object storage costs are usually based on the volume of data stored (GB/month) and any associated retrieval fees. Block storage, such as Amazon Elastic Block Storage (EBS), offers block-level storage volumes that can be attached to Amazon EC2 instances. EBS is commonly used for workloads requiring consistent, low-latency access in GenAI applications, such as model checkpoints, logs, and other intermediate files. Block storage costs are based on storage volume and type, such as solid state disks (SSDs) versus hard disk drives (HDDs).
- Networking costs: Networking costs can add up in cloud deployments, especially for GenAI applications that involve large-scale data transfers across regions or availability zones. Networking cost components include ingress/ egress costs, cross-region transfer costs, NAT gateway costs, and content delivery network (CDN) costs.
- Egress costs include costs for data transferred out of the cloud. If one is serving large AI models to end users or moving data between regions or to on-premises environments, these costs could add up. Ingress costs for the inbound data in the cloud are often lower or free. If an application involves communication between multiple cloud regions, availability zones, or different cloud providers, such as in hybrid or multi-cloud setups, inter-region or outbound data transfer costs could also be significant.
- NAT gateway costs include both fixed hourly charges as well as the data processing charges based on the amount of data transferred. Data transfer costs vary based on the direction of data flow. Inbound data transfer into the cloud from the internet is usually free; however, outbound data transfer from the cloud to the internet can incur charges based on the amount of data (GB).
- Egress costs include costs for data transferred out of the cloud. If one is serving large AI models to end users or moving data between regions or to on-premises environments, these costs could add up. Ingress costs for the inbound data in the cloud are often lower or free. If an application involves communication between multiple cloud regions, availability zones, or different cloud providers, such as in hybrid or multi-cloud setups, inter-region or outbound data transfer costs could also be significant.
We’ve covered various cost components involved in running GenAI applications. Now, let’s explore how to gain granular visibility into infrastructure costs in Kubernetes (K8s) clusters. There are several cost allocation tools available in K8s and cloud environments. Some examples include OpenCost (https://www.opencost.io/), Kubecost (https://www.kubecost.com/), Spot.io (https://spot.io/), Cast.ai (https://cast.ai/), PerfectScale (https://www.perfectscale.io/), IBM Cloudability (https://www.apptio.com/products/cloudability/), Harness (https://www.harness.io/), cloud-provider-specific solutions, and so on. In this chapter, we will explore Kubecost for K8s cluster cost analysis.
Kubecost
Section titled “Kubecost”Kubecost is a cost monitoring and optimization tool designed for K8s environments. It helps to track, allocate, and optimize costs by providing detailed insights into various cost components associated with running workloads in K8s clusters.
Kubecost can help visualize cost components for K8s deployments by providing the following:
- Cost breakdown by namespace, Pod, and service: Kubecost allows us to see detailed costs allocated to different K8s objects, such as namespaces, to track the costs of different teams or applications. It can also highlight the cost attribution at the individual Pod level, services level, or deployments level. Kubecost can aggregate the costs for specific services or deployments, giving a clear picture of how much we’re spending on a microservice or specific deployment. This granular breakdown is especially helpful for a multi-tenant K8s cluster, where multiple teams or services could be sharing the same cluster.
- Compute costs: Kubecost can track the EC2 instance costs, which can help determine whether we are using the most cost-effective node types. Kubecost can also highlight whether any node or compute resource is underutilized.
- Storage costs: Kubecost can track the costs of storage volumes attached to K8s workloads. Kubecost can distinguish between different EBS volume types, such as gp2, gp3, and io1, and their costs, helping you optimize based on performance requirements and costs. It can also detect unused or underutilized volumes.
- Network costs: Kubecost can track networking-related costs, such as data transfer costs between different nodes, regions, or even AWS services. This can help optimize the network configuration and reduce unnecessary cross-region or cross-AZ data transfers.
- Ingress/egress: One can track and visualize the costs of traffic flowing into and out of your K8s cluster, which is particularly relevant when serving external applications or users.
- Load balancers: Kubecost identifies and breaks down the costs of load balancers (such as AWS NLB or ALB) that are associated with K8s services or ingress resources.
- Integration with AWS Cost and Usage Reports (CUR): Kubecost can integrate with AWS CUR (https://docs.aws.amazon.com/cur/latest/userguide/what-is-cur.html) to provide a comprehensive view of costs, including non-K8s AWS services that your EKS workloads rely on, such as Amazon S3 or RDS. If you have multiple EKS clusters, Kubecost can also aggregate costs across all your clusters and provide insights at a global level or drill down into specific clusters for more detailed cost analysis.
Kubecost supports cost allocation by labels, which is especially useful for multi-tenant environments where one needs to attribute costs to different teams, projects, or environments (e.g., development, QA, staging, or production). Kubecost provides historical cost tracking and allows you to visualize cost trends over time.
Kubecost can not only help you to visualize costs, but also provide actionable recommendations to optimize spending, such as right-sizing recommendations by analyzing resource usage (CPU, memory, storage) and recommending resizing your workloads to avoid overprovisioning or underutilization of resources. Kubecost can suggest where you could switch to EC2 Spot Instances to save on compute costs, which is especially relevant for non-critical or interruptible workloads.
Setting up Kubecost
Section titled “Setting up Kubecost”Kubecost can be installed in our EKS cluster as a Helm chart. Refer to the Amazon EKS integration in the Kubecost documentation at https://www.ibm.com/docs/en/kubecost/self-hosted/2.x?topic=installations-amazon-eks-integration for various installation options.
In our setup, we will install Kubecost using the Terraform Helm provider. Download the addons.tf file from https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch7/addons.tf to the Terraform project folder and run the following commands:
$ terraform init$ terraform plan$ terraform apply -auto-approveYou can verify the installation using the following command, which displays the status, version, and other details of the deployment:
$ helm list -n kubecostNAME NAMESPACE STATUS CHARTkubecost kubecost deployed cost-analyzer-2.7.2To access the Kubecost UI console, run the following command to enable port forwarding:
$ kubectl port-forward -n kubecost deployment/kubecost-cost-analyzer 9090:9090You can now access the Kubecost UI by visiting http://localhost:9090 in your web browser. In the Kubecost UI console, expand the Monitor section in the left-hand side panel. You will see various dashboards such as Allocations, Assets, Cloud Costs, Network, Clusters, External Costs, and so on, which provide cost visualization of K8s workloads, savings recommendations, and governance tools. For example, select Allocations to navigate to the Allocations dashboard, as shown in Figure 7*.1*, which allows you to view the allocated spend across all native K8s constructs such as namespaces, services, deployments, and K8s labels.

Figure 7.1 – The Kubecost Allocations dashboard
To view the costs of our GenAI applications deployed in Chapter 5, change the Aggregate By query from Namespace to Deployment and apply the default namespace filter. You will see the costs for the fine-tuned Llama 3 deployment, RAG API, and Chatbot UI applications, as shown in Figure 7*.2*.
Important note
Kubecost only monitors the costs from the time it is installed on the cluster, so the costs for the Llama 3 fine-tuning job are not available. You can rerun the job to view those costs.

Figure 7.2 – Cost analysis of GenAI applications
Refer to the Kubecost documentation at https://www.ibm.com/docs/en/kubecost/self-hosted/2.x?topic=navigating-kubecost-ui to learn more about these dashboards.
In this section, we explored the various cost components involved in running GenAI applications on K8s, such as compute, storage, networking, and so on. We also looked into various tools for gaining deeper visibility into K8s workload costs, deployed Kubecost on our EKS cluster, and used the Allocations dashboard to aggregate costs by namespace and deployment.
In the next section, we will dive into various cost optimization techniques.
Cost optimization techniques
Section titled “Cost optimization techniques”To effectively reduce the costs of running GenAI workloads on K8s, it is important to optimize each of the key cost components: compute, storage, and networking. In this section, we will discuss various strategies for each of these components to lower the costs while maintaining the best performance.
Compute best practices
Section titled “Compute best practices”Compute is often the most significant component of GenAI costs, as these applications typically require access to specialized hardware such as GPUs, which are expensive and scarce. Let’s look at various techniques to efficiently utilize the compute resources and lower the costs.
Right-sizing resources
Section titled “Right-sizing resources”Right-sizing resources is the most important step in optimizing the cost efficiency of GenAI workloads. This involves understanding the nature of the applications by profiling them and configuring the appropriate resource requests (CPU, memory, GPU) based on the actual utilization of the K8s workloads.
Right-sizing resources in K8s can minimize waste and maximize efficiency. For example, under-provisioning resources can lead to performance degradation and poor user experience, whereas over-provisioning can result in unnecessary cloud spending. By accurately setting resource requests and limits, the user can strike a balance between performance and cost. Selecting the right size instances enhances cluster density, allowing more workloads to run on fewer nodes, further optimizing costs.
There are a number of tools in the K8s community that help us estimate the resource requests and limits. Some notable ones are Goldilocks (https://goldilocks.docs.fairwinds.com/), StormForge (https://stormforge.io/optimize-live/), KRR (https://github.com/robusta-dev/krr), Kubecost, and so on. We will delve into a few details about Goldilocks here.
Goldilocks is a tool designed to help K8s users optimize their resource requests and limits, which improves the efficiency and cost-effectiveness of K8s clusters. Goldilocks uses Vertical Pod Autoscaler (VPA) in Recommender mode to suggest the optimal resource requests and limits for your K8s Pods. VPA monitors the actual CPU and memory usage of running Pods over time. It gathers usage data directly from K8s metrics. Goldilocks takes the historical CPU and memory utilization data from VPA and provides recommended resource requests and limits based on the actual needs of your application. These recommendations help ensure that you’re not over-provisioning or under-provisioning resources. Goldilocks provides a dashboard or CLI tool to visualize its findings. It displays the current resource requests/limits and the recommended values based on the observed usage.
Refer to the Goldilocks installation guide at https://goldilocks.docs.fairwinds.com/installation/ for detailed instructions on setting up Goldilocks in your EKS cluster. After the installation, you can enable monitoring by labeling the target namespace with goldilocks.fairwinds.com/enabled=true. For example, you can execute the following command to enable monitoring on the default namespace:
$ kubectl label namespace default goldilocks.fairwinds.com/enabled=truenamespace/default labeledOnce the target namespaces are labeled, you can view the recommendations in the Goldilocks UI dashboard, as shown in Figure 7*.3*, which displays resource usage recommendations for our Chatbot UI application.

Figure 7.3 – The Goldilocks dashboard
Kubecost also provides right-sizing recommendations for the K8s workloads. Select Savings from the left-hand side menu in the Kubecost UI console to view the cost savings recommendations. Savings Insights provides various recommendations, such as right-sizing cluster nodes, containers, remedying abandoned workloads, and so on, to lower the K8s and cloud costs, as shown in Figure 7*.4*.

Figure 7.4 – Kubecost savings insights
Learn more about these insights in the Kubecost documentation at https://www.ibm.com/docs/en/kubecost/self-hosted/2.x?topic=ui-savings.
Compute capacity options
Section titled “Compute capacity options”When deploying workloads on the cloud, you have several options for managing compute capacity. These options vary in terms of cost, performance, and availability. The following is a breakdown of the different capacity types available for Amazon EKS, including Reserved Instances (RIs), Spot Instances, and x86 versus ARM architecture choices:
- EC2 on-demand instances (https://aws.amazon.com/ec2/pricing/on-demand/) are the default capacity type when deploying on EKS. They provide a flexible compute option without any long-term commitments, and you pay by the minute or second for the instances you use. On-demand instances are the most expensive, but they offer the highest level of flexibility and availability. This flexibility is especially beneficial during development and experimentation phases of GenAI workloads, where workload patterns and resource requirements may vary significantly.
- EC2 RIs (https://aws.amazon.com/ec2/pricing/reserved-instances/) provide a significant discount (up to 72%) compared to on-demand pricing in exchange for a one- or three-year commitment. RIs are well-suited for predictable workloads where you expect consistent usage over time. There are two different kinds of Ris:
- Standard RIs: These provide the largest discounts but require a longer commitment for a given instance type. Usually, the larger the commitment period, the larger the discount.
- Convertible RIs: These offer the flexibility to change the instance families, operating system, or tenancy during the commitment period. This flexibility comes at a slightly smaller discount compared to that of Standard RIs.
- Standard RIs: These provide the largest discounts but require a longer commitment for a given instance type. Usually, the larger the commitment period, the larger the discount.
- EC2 Spot Instances (https://aws.amazon.com/ec2/spot/) allow you to use spare EC2 capacity at a significantly lower cost (up to 90%). However, Spot Instances can be interrupted by AWS when it needs the capacity back, so they are suited for fault-tolerant workloads. You’ll receive a two-minute notice before your Spot Instance is reclaimed by AWS. It’s essential to architect your workloads to handle interruptions gracefully, using techniques such as checkpointing, distributed job management, or backup on-demand instances. Spot Instances can be used for batch processing, stateless web servers, CI/CD pipelines, or any other workloads that can tolerate occasional interruptions or delays. Tools such as Ray, Kubeflow, and Horovod (https://github.com/horovod/horovod) can be configured to leverage Spot Instances for running distributed training/fine-tuning of GenAI workloads, offering features such as checkpointing, interruption handling, and so on. When combined with a compute autoscaling solution such as Karpenter, these tools can automatically fall back to on-demand capacity when spot capacity is not available, ensuring both cost efficiency and reliability.
- Savings Plans (https://docs.aws.amazon.com/savingsplans/latest/userguide/what-is-savings-plans.html) offer an alternative to RIs by providing flexibility in instance types and sizes while providing a significant discount for committing to a consistent amount of usage over a one- or three-year period. You can apply Savings Plan discounts across different EC2 instance families, AWS regions, and even compute services such as EC2, AWS Fargate, and AWS Lambda.
- AWS Graviton instances (ARM-based) (https://aws.amazon.com/ec2/graviton/) AWS offers two main processor architectures for EC2 instances: x86-based (typically Intel or AMD processors) and ARM-based (AWS Graviton processors). Choosing between these can impact both performance and cost. Graviton-based instances can offer up to 40% better price performance for various applications. Refer to the AWS documentation at https://aws.amazon.com/ec2/instance-explorer/ to learn more about various Graviton instance types and respective use cases. These instances provide a cost-effective and efficient compute option for CPU-intensive parts of GenAI workloads, such as data preparation, lightweight model inferencing (when GPU acceleration is not needed), chatbot UIs, and other microservice-based workloads.
- AWS Fargate (https://aws.amazon.com/fargate/) is a serverless compute engine for containers that works with both Amazon ECS and Amazon EKS. It allows the running of K8s Pods without managing the underlying EC2 infrastructure. This provides a serverless experience, where you only pay for the compute resources used by the Pods. With the Fargate capacity type, there is no need to manage EC2 instances for OS updates, patching, or node scaling. Like Graviton, we can utilize AWS Fargate for data preparation, chatbot interfaces, and other microservice-based workloads.
- EC2 Capacity Blocks for ML (https://aws.amazon.com/ec2/capacityblocks/) provides reserved accelerated compute capacity to run AI/ML workloads in AWS for a future start date. EC2 Capacity Blocks supports EC2 P5e (https://aws.amazon.com/ec2/instance-types/p5/), P5 (https://aws.amazon.com/ec2/instance-types/p5/), P4d (https://aws.amazon.com/ec2/instance-types/p4/), and other EC2 instances powered by NVIDIA GPUs, Trn1 and Trn2 instances powered by AWS Trainium processor. These help to ensure the guaranteed capacity for model experimentation, scheduling large training, and fine-tuning jobs. Capacity Blocks are co-located in Amazon EC2 UltraClusters (https://aws.amazon.com/ec2/ultraclusters/), designed for high-performance ML workloads and providing low-latency, high-throughput network connectivity for distributed training.
In this section, we explored best practices for optimizing the compute costs associated with running GenAI workloads in K8s clusters. Compute resources, including CPU, GPU, and custom accelerator nodes, are often the largest contributors to operational expenses, especially for GenAI models. We covered techniques such as right-sizing resources and using tools such as Kubecost and Goldilocks to get right-sizing recommendations, using different capacity types such as Spot Instances, RIs, and Capacity Blocks, and using Savings Plans for different types of workloads. By following these practices, you can minimize compute costs while maintaining the performance and scalability of GenAI workloads.
Networking best practices
Section titled “Networking best practices”To achieve high availability in Amazon EKS, it is recommended to distribute workloads across multiple Availability Zones (AZs). This architecture enhances system reliability, especially during outages or infrastructure failures in an AZ. However, data transfer, latency between the K8s Pods, nodes, and AZs can quickly add up, especially for resource-intensive workloads such as model training and data preparation tasks. To control the data transfer costs that arise from communication between AZs or regions, effective network management is needed. Let’s look at various techniques to minimize the networking costs while maintaining performance.
Pod-to-pod communication
Section titled “Pod-to-pod communication”Inter-pod traffic across AZs can incur significant costs. Limiting cross-zone traffic by aligning communication within the same AZ helps reduce these expenses. Topology Aware Routing (https://kubernetes.io/docs/concepts/services-networking/topology-aware-routing/) ensures that traffic between services is routed to the nearest Pod in the same AZ. K8s uses EndpointSlices (https://kubernetes.io/docs/concepts/services-networking/endpoint-slices/) with zone-specific hints, ensuring kube-proxy directs traffic based on the origin zone, minimizing inter-AZ traffic. However, there are many considerations to be made for this to work effectively in a K8s cluster. Refer to the AWS blog at https://aws.amazon.com/blogs/containers/exploring-the-effect-of-topology-aware-hints-on-network-traffic-in-amazon-elastic-kubernetes-service/ for a deeper understanding.
Workloads can also be restricted to specific AZs using Cluster Autoscaler (CA) or Karpenter. This avoids cross-AZ traffic, reducing network-related costs and improving latency. For example, Karpenter allows specifying worker node zones with the label topology.kubernetes.io/zone, as shown in the following example:
apiVersion: karpenter.sh/v1kind: NodePoolmetadata: name: single-az-examplespec:... requirements: - key: "topology.kubernetes.io/zone" operator: In values: ["us-west-2a"]...Load balancer configuration
Section titled “Load balancer configuration”AWS Load Balancer Controller (https://kubernetes-sigs.github.io/aws-load-balancer-controller/latest/) manages ELB resources, including application and network load balancers. In IP mode (https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-register-targets.html#register-ip-addresses), where K8s Pods are registered directly as ELB targets, traffic is routed straight to the destination Pods. This reduces extra network hops, lowers network latency, and eliminates the inter-AZ data transfer costs. In Instance mode (https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-register-targets.html#register-instances), traffic is first routed to the EC2 worker nodes and then forwarded to the appropriate K8s Pods. This additional routing step can result in extra network hops and may incur inter-AZ data transfer costs, especially when the K8s Pod is in a different AZ. Refer to the AWS blog at https://aws.amazon.com/blogs/networking-and-content-delivery/exploring-data-transfer-costs-for-classic-and-application-load-balancers/ to understand the data transfer costs when using application load balancers.
Data transfer and VPC connectivity
Section titled “Data transfer and VPC connectivity”To reduce data transfer costs between services, VPC endpoints (https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/what-are-vpc-endpoints.html) enable direct access to AWS services without routing through the public internet. This eliminates the need for deploying an internet gateway (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html) and network address translation (NAT) gateway (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) to communicate with AWS services. For workloads spread across different VPCs, VPC peering (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-peering.html) or an AWS Transit Gateway (https://docs.aws.amazon.com/vpc/latest/userguide/extend-tgw.html) is recommended to enable low-cost, inter-VPC communication.
Optimizing image pulls from Amazon ECR
Section titled “Optimizing image pulls from Amazon ECR”This strategy can help reduce networking costs and improve K8s Pod startup times. In-region image pulls from Amazon ECR are free, but you will be charged a NAT gateway data processing fee. So, you can utilize the VPC endpoints of Amazon ECR and Amazon S3 to privately access the ECR images. For large GenAI workloads, pre-caching container images in custom AMIs can further optimize the image pull times during worker node/Pod startup. This approach minimizes data transfer during scaling events and speeds up instance readiness, which is particularly beneficial for dynamic, auto-scaling environments. Refer to the AWS blog at https://aws.amazon.com/blogs/containers/start-pods-faster-by-prefetching-images/ for a deeper understanding of how this works.
In this section, we explored best practices for optimizing networking costs for running GenAI workloads in K8s clusters. Effective networking strategies can help reduce the significant costs associated with data transfer, NAT gateways, and load balancing. Using techniques such as Topology Aware Routing and IP targets in ALB can help reduce latency and data transfer costs. We also discussed the benefits of optimizing image pulls from ECR to speed up the startup times and reduce networking costs.
In the next section, we will explore storage-related best practices in K8s clusters.
Storage best practices
Section titled “Storage best practices”There are multiple storage options available in a K8s environment, and selecting the right one is essential to optimize application performance and cost. Depending on the workload, one could use either ephemeral storage or persistent storage for their applications.
Ephemeral storage
Section titled “Ephemeral storage”Ephemeral volumes are temporary storage volumes that do not persist beyond a Pod’s life cycle, making them suitable for scratch space or caching. These volumes are often backed by the root disk of the host system or RAM, meaning they do not persist once the Pod is terminated. For cost efficiency, it’s important to properly configure ephemeral storage to avoid over-provisioning, and where possible, leverage node-local storage for temporary tasks to reduce reliance on external storage systems, thus lowering costs.
Object storage
Section titled “Object storage”While ephemeral and EBS volumes provide low-latency, high-performance storage for many workloads, object storage solutions such as Amazon S3 offer a flexible, scalable, and cost-effective alternative for storing large datasets, model artifacts, and logs. The Mountpoint for Amazon S3 CSI driver (https://github.com/awslabs/mountpoint-s3-csi-driver) enables you to mount an S3 bucket as a filesystem inside the K8s Pods, allowing applications to interact with object storage using familiar filesystem semantics. It offers significant performance gains compared to traditional S3 access methods, making it ideal for data-intensive workloads and AI/ML training.
The Mountpoint for S3 CSI driver supports both Amazon S3 Standard and S3 Express One Zone storage classes. S3 Express One Zone is a high-performance storage class designed for single-AZ deployments. It offers consistent, single-digit-millisecond data access, making it ideal for frequently accessed data and latency-sensitive applications. By co-locating storage and compute resources within the same AZ, you can optimize performance and potentially reduce networking costs.
In addition to performance considerations, optimizing object storage costs is essential when working with large-scale training datasets. Best practices include selecting the appropriate S3 storage class based on the access patterns. For example, use S3 Standard or S3 Intelligent-Tiering for frequently accessed data, and transition infrequently accessed data to S3 Infrequent Access or archival classes such as Glacier. Implement life cycle policies to automate transitions and data expirations, thereby reducing unnecessary storage costs. Refer to the AWS documentation at https://aws.amazon.com/s3/storage-classes/ for a deeper understanding of the various S3 storage classes.
When using Mountpoint for S3 CSI driver, you can attach an existing S3 bucket to K8s Pods by creating a PersistentVolume, as shown in the following:
apiVersion: v1kind: PersistentVolumemetadata: name: s3-demo-pvspec: capacity: storage: 1200Gi # Ignored, required accessModes: - ReadWriteMany mountOptions: - allow-delete - region us-west-2 csi: driver: s3.csi.aws.com volumeHandle: s3-csi-driver-volume volumeAttributes: bucketName: <Your-S3-Bucket-Name>By leveraging the Mountpoint-S3 and adhering to cost-effective storage best practices, you can seamlessly integrate Amazon S3 object storage into your K8s workloads. This approach enables your GenAI workloads to access large-scale, cost-effective storage with familiar filesystem semantics while optimizing both performance and cost.
EBS volumes
Section titled “EBS volumes”Amazon EBS volumes provide block-level persistent storage. EBS volumes are managed via the Amazon EBS CSI driver, enabling dynamic provisioning through K8s. The Container Storage Interface (CSI) is a standardized K8s API that ensures interoperability between K8s and external storage systems. K8s applications request storage by creating Persistent Volume Claims (PVCs) specifying the size and access mode. The EBS CSI driver provisions the EBS volume based on the linked StorageClass. For example, following YAML code will create a gp3 storage class:
apiVersion: storage.k8s.io/v1kind: StorageClassmetadata: name: gp3-scprovisioner: ebs.csi.aws.comparameters: type: gp3 encrypted: "true" fsType: ext4allowVolumeExpansion: truereclaimPolicy: DeleteA reclaim policy for StorageClass could be either delete or retain. The delete policy ensures that the PersistentVolume is automatically deleted when the associated Pod is removed. The retain policy keeps the PV even after the PVC is deleted. The volume stays intact with all its data, but becomes unbound and available for manual intervention.
The following YAML file is now creating a PVC, which is linked to the previous storage class for 10 GB of storage:
apiVersion: v1kind: PersistentVolumeClaimmetadata: name: demo-pvcspec: accessModes: - ReadWriteOnce resources: requests: storage: 10Gi storageClassName: gp3-scFor cost optimization, it is a good idea to ensure that the correct amount of storage is claimed based on your application’s needs. Over-provisioning large volumes that are not fully utilized leads to unnecessary costs. Similarly, it’s common for unused PVs and EBS snapshots to accumulate over time, so one should keep monitoring their storage costs or use delete as a reclaim policy. You can use Kubecost to get insights into unclaimed volumes, orphaned resources, persistent volume right-sizing recommendations, and so on. Open the Kubecost UI console and select Savings -> Insights from the left-hand side menu to navigate to the Savings page, where you can view the cost savings recommendations, as shown in Figure 7*.5* and Figure 7*.6*.

Figure 7.5 – An overview of unclaimed volumes in the Kubecost UI console
These insights help you identify cost-saving opportunities by highlighting persistent volumes that are allocated but not actively used. By analyzing these patterns, Kubecost enables you to take informed actions such as reclaiming unused resources or resizing existing volumes to better fit your workload requirements, as shown in the Figure 7.6.

Figure 7.6 – An overview of PV right-sizing recommendations in the Kubecost UI console
For optimized costs, gp3 volumes are recommended, as they offer up to 20% lower costs compared to gp2 and allow independent scaling of IOPS and throughput without increasing volume size. For high-performance needs, io2 Block Express volumes support up to 256,000 IOPS, but they are more expensive and require specific EC2 instance types.
For workloads with less frequent access to data, such as logs and backups, one could use Cold HDD (sc1) or Throughput Optimized HDD (st1). These options are cheaper than SSD-backed volumes. Refer to the Amazon EBS pricing page at https://aws.amazon.com/ebs/pricing/ for detailed pricing.
A few other considerations to make when optimizing storage costs in K8s applications are as follows:
- Optimize container image storage: Container images can consume a significant amount of storage, especially when large, multi-layer images are used in an Amazon EKS cluster. Optimizing it is crucial for reducing both storage costs and the time it takes to pull images during startup. To achieve this, it’s best to use smaller, lightweight parent images where possible. Additionally, by employing multi-stage builds (https://docs.docker.com/build/building/multi-stage/), only the necessary components are included in the final container image, further decreasing image size. These optimizations not only save storage space but also lead to faster deployment times and reduced costs for both storing and pulling container images.
- Use data retention policies: Implement data retention policies to automatically delete old, unnecessary datasets such as logs, metrics, and backups that accumulate over time. Tools such as Elasticsearch and AWS CloudWatch Logs offer controls to set appropriate retention policies to delete old logs and reduce storage costs. Similarly for backups, set appropriate retention policies, ensuring that only necessary backups are retained, while old, redundant backups are deleted.
In this section, we discussed various available storage options and how to use CSI drivers to dynamically provision the storage volumes in K8s clusters. We also explored the importance of reducing the container image size to not only reduce the storage costs but also improve the startup times of K8s Pods.
Summary
Section titled “Summary”In this chapter, we explored the best practices for optimizing the cost of deploying GenAI applications in the cloud by focusing on three key components: compute, storage, and networking. We also introduced tools such as Kubecost and Goldilocks to monitor resource utilization and ensure efficient resource allocation.
For compute costs, selecting the appropriate instance types is essential. It’s crucial to monitor resource utilization to ensure workloads run on optimally sized instances. For storage, choosing the right storage type is the key to optimizing the storage costs of large datasets needed for model training and inference.
Kubecost is an effective tool for monitoring and optimizing the cost of K8s clusters. It provides detailed cost breakdowns by namespaces, Pods, and services, helping attribute expenses to individual teams or applications. Kubecost also identifies underutilized nodes, recommends more cost-effective instance types, and detects storage and networking inefficiencies, such as unnecessary inter-AZ data transfers. Goldilocks leverages the VPA to analyze historical CPU and memory usage, providing recommendations for right-sizing resource requests and limits.
On the networking front, we discussed the importance of aligning Pod communication within the same AZ to minimize cross-AZ traffic costs. Using Topology Aware Routing ensures that traffic is routed within the AZ, reducing inter-AZ transfer fees.
This chapter also highlighted the importance of continuous monitoring, right-sizing resources, and making strategic trade-offs across compute, storage, and networking to optimize costs effectively.
In the next chapter, we will dive deeper and cover the networking best practices for deploying GenAI applications in K8s.
Get This Book's PDF Version and Exclusive Extras
|