Scaling GenAI Applications on Kubernetes
local graph
Chapter 6 — Scaling GenAI Applications on Kubernetes
Section titled “Chapter 6 — Scaling GenAI Applications on Kubernetes”In this chapter, we will cover application scaling strategies and best practices for Kubernetes. Application scaling is a process where K8s can dynamically scale the resources to match the application demand, ensuring efficient and cost-effective resource utilization and optimal application performance. Kubernetes provides different scaling mechanisms to scale applications based on metrics such as CPU usage, memory, or custom metrics.
In this chapter, we’re going to cover the following main topics:
- Scaling metrics
- HorizontalPodAutoscaler (HPA)
- VerticalPodAutoscaler (VPA)
- Kubernetes Event-Driven Autoscaler (KEDA)
- Cluster Autoscaler (CA)
- Karpenter
Scaling metrics
Section titled “Scaling metrics”To scale applications correctly, it is essential to choose the right metrics to ensure efficient resource utilization and a seamless end user experience. These metrics can be divided into conventional and custom metrics.
Conventional metrics
Section titled “Conventional metrics”These are common metrics in Kubernetes used for horizontal or vertical scaling:
- CPU usage: This measures the percentage of CPU utilization. High CPU utilization might indicate that the application is under heavy load, requiring more instances (Pods) to handle the demand, whereas a constantly low CPU usage might indicate the overprovisioning of resources, and the number of Pods can be scaled down.
- Memory usage: This measures the amount of memory consumed by a Pod. Like CPU, high memory usage can signal that the application is handling a large amount of data, meaning more resources are needed to prevent memory shortages. When a process inside a container exceeds the memory limit, the container will be terminated by the container runtime (CRI), which is different from the CPU limit. If a CPU limit is set and a container exceeds that limit, the container will not get terminated but rather throttled or slowed down. Generally, it is not a best practice to use memory usage as a scaling metric because applications are often poor at memory management.
Custom metrics
Section titled “Custom metrics”Custom metrics allow K8s scaling based on more application or use case-specific metrics, allowing better granular control over the application’s performance. Some examples of custom metrics are as follows:
- HTTP requests rate: This measures the number of HTTP/HTTPS requests or API calls the application receives per second. We could use monitoring tools, such as Prometheus, to track the request rates and scale the application when requests spike and exceed a certain threshold.
- Queue length: This measures the number of unprocessed jobs or messages in a queue, such as Amazon SQS or RabbitMQ. Queue backlogs indicate that the application is not able to keep up with the load and needs more resources to process jobs in a timely manner. It is a critical metric, especially in event-driven architecture (EDA). K8s scaling mechanisms, such as KEDA, support scaling based on queue metrics.
- Latency/response time: This measures the time it takes for the application to respond to requests. High latency often signals that the application is struggling under the current load, and scaling out additional instances can help maintain low response times.
- Error rate: This measures the number of failed requests. An increase in the error rate could indicate that the current number of resources is insufficient to handle the load, leading to failures; scaling up the resources might be required.
- Concurrency/active sessions: This measures the number of active connections, users, or sessions interacting with the application. For applications such as online games or video streaming platforms, the number of active users could be a critical indicator of the application load.
- GPU utilization: This measures the percentage of GPU capacity consumed by an application. When scaling GenAI applications on K8s, using GPU utilization as a scaling metric is effective because of heavy reliance and the indication of the load on the application. With NVIDIA GPUs, metrics are exported using the DCGM-Exporter addon (https://github.com/NVIDIA/dcgm-exporter), which can be installed via Helm, allowing an observability agent (such as Prometheus) to scrape these metrics. We will configure this in our EKS cluster as part of Chapter 12.
These are some of the commonly used metrics used in K8s to scale the resources. Some applications may require a mix of metrics. For example, a web application might use network I/O and request rate together to ensure optimal resource utilization and performance. Custom metrics are not available by default for K8s autoscaling; a custom metrics adapter needs to be installed to make them available from respective metric sources. This adapter acts as a bridge between the metrics system and K8s, exposing the metrics via K8s custom metrics API. Some examples are prometheus-adapter (https://github.com/kubernetes-sigs/prometheus-adapter) and Datadog Cluster Agent (https://docs.datadoghq.com/containers/guide/cluster_agent_autoscaling_metrics).
In this section, we discussed different types of scaling metrics, such as conventional and custom metrics, and had a look at some examples. We also discussed the custom GPU utilization metric and saw that it is an effective measure to scale the GenAI workloads. Next, let’s explore horizontal Pod autoscaling and see how these metrics can be used to autoscale K8s Pods.
HorizonalPodAutoscaler (HPA)
Section titled “HorizonalPodAutoscaler (HPA)”HPA (https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) is a K8s feature that adjusts the number of Pods in a deployment based on user-defined metrics, such as CPU or memory utilization. The primary goal of HPA is to ensure that applications can handle varying loads by dynamically scaling in or out the number of Pods. HPA does not apply to objects that can’t be scaled, such as DaemonSets.
HPA uses a metrics server or monitoring system, such as Prometheus, to collect real-time data on the defined metrics. HPA has a controller component that runs in the Kubernetes control plane. It periodically checks the current metrics of the target application, such as deployment, and compares it to the desired thresholds specified in the HPA resource configuration.
Based on the metrics, the controller adjusts the desired number of Pods. If resource usage, such as CPU utilization, exceeds the threshold, HPA increases the number of Pods, whereas if the usage drops below the threshold, HPA decreases the number of Pods, as shown in Figure 6*.1*.

Figure 6.1 – HPA overview
The following YAML file indicates how HPA can be implemented for our e-commerce chatbot UI deployment in K8s:
apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: chatbot-ui-hpaspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: chatbot-ui-deployment minReplicas: 1 maxReplicas: 5 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70In this example, we are setting kind to HorizontalPodAutoscaler, which specifies that this manifest is for an HPA, and setting its name to chabot-ui-hpa. In the spec section, we are setting the scaling target for this HPA as chatbot-ui-deployment, which is a deployment, and apps/v1 is the API version for the target resource.
Next, we set the minimum number of replicas to 1 (minReplicas: 1) and the maximum number of replicas to 5 (maxReplicas: 5). Finally, we set the metrics that HPA can monitor and use to make scaling decisions. In this example, we are using average CPU utilization across all the chatbot-ui-deployment deployment Pods as the metric.
In the target specification, averageUtilization: 70 sets the target CPU utilization to 70. If the average CPU utilization exceeds 70%, HPA will start scaling up the number of replicas to meet this target; however, it will not exceed five replicas due to the maximum limit we defined. Once the CPU utilization drops below 70%, it will start scaling down but will ensure that there is still one replica running all the time (minReplicas). You can also use K8s imperative commands to create and manage HPA resources. For example commands, refer to official K8s documentation at https://kubernetes.io/docs/tasks/manage-kubernetes-objects/imperative-command/.
You can download the HPA manifest from the GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch6/chatbot-ui-hpa.yaml and execute the following command to apply the HPA policy in our EKS cluster.
$ kubectl apply -f chatbot-ui-hpa.yamlhorizontalpodautoscaler.autoscaling/chatbot-ui-hpa createdTo prevent frequent scaling up and down, the following HPA behavior configuration can be used:
behavior: scaleDown: stabilizationWindowSeconds: 180 policies: - type: Percent value: 50 periodSeconds: 15 scaleUp: stabilizationWindowSeconds: 0 policies: - type: Pods value: 2 periodSeconds: 15 selectPolicy: MaxThe scaleDown section controls how fast the HPA can scale down or remove the replicas. The maximum allowed scale-down has been set to 50% in this example, which means that HPA can remove up to 50% of the current replicas during each scale-down event. periodSeconds defines the time window in seconds over which the scaling rule is evaluated. stabilizationWindowSeconds specifies the amount of time (in seconds) that HPA will wait before scaling down after detecting lower resource utilization. This helps prevent frequent and aggressive scaling down that might occur due to temporary drops in usage.
In this case, the stabilization window is set to 180 seconds, meaning that HPA will wait for 3 minutes before it reduces the number of replicas after a drop in load.
The scaleUp section of behavior classification controls how fast the HPA can scale up or add new Pods. In this case, we are defining scale-up policies using a fixed number of Pods instead of percentage based approach. A percentage based policy would increase the number of Pods by a certain percentage of the current replica count. For example, if we have 5 Pods and the policy allows a 60% increase, HPA could scale up by 3 Pods.
In this example, scaling is done in fixed increments of two Pods and HPA will allow adding up to two Pods within every 15-second window, if more replicas are required. We have set stabilizationWindowSeconds to 0, meaning there’s no delay before scaling up.
In this walkthrough, we created an HPA policy based on the Pod-level metrics, which aggregate the resource usage of all containers within a Pod. However, in multi-container Pods, this metric might not accurately represent the performance of an individual container. To address this, K8s introduced container resource metrics that allow HPA to track the resource usage of specific containers across Pods when scaling the target resource. This approach enables you to set scaling thresholds for the containers that are most critical to your application. For example, if your Pod includes a web application and a sidecar container that provides logging, you can configure HPA to scale based solely on the web application’s CPU utilization while ignoring the sidecar’s resource use. The following code snippet demonstrates how to use the CPU utilization of the web-app container to scale the overall deployment:
type: ContainerResourcecontainerResource: name: cpu container: web-app target: type: Utilization averageUtilization: 60In this section, we explored HPA, a K8s feature designed to automatically adjust the number of Pods in a K8s Deployment, StatefulSet, or ReplicaSet based on user-defined metrics such as CPU, memory, or GPU utilization. Its primary goal is to maintain an adequate number of K8s Pods to handle dynamic workloads effectively. We also covered how to configure HPA policies and customize the scaling behavior. Next, let’s dive into VPA.
VerticalPodAutoscaler (VPA)
Section titled “VerticalPodAutoscaler (VPA)”VPA can adjust the resource requests and limits for the CPU and memory of the Pods based on actual usage and configuration. This differs from HPA, which adjusts the number of Pods based on the metrics defined. VPA has four operating modes:
- Off: In this mode, VPA only provides resource recommendations, but does not apply any changes.
- Auto: VPA applies changes to resource requests and restarts the Pods, if needed.
- Recreate: VPA applies changes on Pod creation and updates them on existing Pods by evicting them.
- Initial: VPA applies resource recommendations only when new Pods are created or existing Pods are restarted, without interfering with the running Pods.
VPA collects resource usage data via the K8s Metrics API and suggests optimal CPU and memory values for resource requests and limits. In Auto mode, it can automatically evict Pods so that they are rescheduled with updated resource requests, as shown in Figure 6*.2*.

Figure 6.2 – VPA overview
Unlike HPA, VPA is not included with K8s by default; it is a separate project available on GitHub at https://github.com/kubernetes/autoscaler/tree/master/vertical-pod-autoscaler. Install the VPA add-on by following the instructions provided at https://github.com/kubernetes/autoscaler/blob/master/vertical-pod-autoscaler/docs/installation.md.
The following YAML file implements VPA in our e-commerce chatbot UI application deployed in K8s:
apiVersion: autoscaling.k8s.io/v1kind: VerticalPodAutoscalermetadata: name: chatbot-ui-vpaspec: targetRef: apiVersion: apps/v1 kind: Deployment name: chatbot-ui-deployment updatePolicy: updateMode: "Auto" resourcePolicy: containerPolicies: - containerName: "*" minAllowed: cpu: "1000m" memory: "2Gi" maxAllowed: cpu: "2000m" memory: "4Gi" controlledValues: "RequestsAndLimits"You can download the VPA manifest from the GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch6/chatbot-ui-vpa.yaml and execute the following command to apply the VPA policy in our EKS cluster:
$ kubectl apply -f chatbot-ui-vpa.yamlverticalpodautoscaler.autoscaling.k8s.io/chatbot-ui-vpa createdIn this example, we are setting kind to VerticalPodAutoscaler and updateMode to Auto, which means that VPA will automatically adjust resource requests and limits. The containerName * wildcard indicates that the policy should be applied to all containers in the Pod.
maxAllowed limits ensure that VPA does not set resource values beyond the specified range. In this configuration, the minAllowed limits are defined as 1000m (equivalent to one vCPU) and 2 GB of memory, while the maximum allowed CPU is 2000m (or two vCPUs) with 4 GB of memory. Defining controlledValues as RequestsAndLimits means that VPA should manage both resource requests and limits. Resource requests are the amount of CPU or memory that a Pod requests from the Kubernetes scheduler when it starts. We can also set this to RequestsOnly if we want VPA to adjust the resource requests only, but not the limits.
Combining HPA and VPA
Section titled “Combining HPA and VPA”It is recommended not to combine HPA and VPA in the same cluster (unless VPA is set to “off”), as it can result in potential conflicts. For example, VPA adjusts the CPU/memory resource requests and limits for a Pod, while HPA scales the number of Pods based on current utilization. If HPA and VPA are used simultaneously, VPA changes might confuse HPA, as the resource usage of a single Pod fluctuates frequently, affecting the metrics used by HPA to scale.
In this section, we explored VPA and its operating modes, along with an example manifest. VPA monitors resource usage of workloads and automatically adjusts the resource requests to optimize resource allocation in a K8s cluster. We also discussed potential conflicts that arise by combining HPA and VPA in auto-operating mode simultaneously.
With cloud adoption, there is a growing trend of microservice and EDA adoption. In this implementation, different building blocks are divided into microservice-based implementations, which are self-contained and talk to each other only through API calls. This implementation allows easier updates and the flexibility to add new features.
KEDA (https://keda.sh/) is an open source project that brings event-driven autoscaling to Kubernetes. It extends Kubernetes’ built-in HPA by allowing applications to scale based on external event sources, such as message queue depth, event stream size, or any custom metrics.
A KEDA ScaledObject is a custom resource that defines how a target (e.g., a Deployment) should be autoscaled based on event-driven or external metrics. When we define a ScaledObject in KEDA, it automatically creates an HPA resource behind the scenes. The HPA resource then scales the deployment based on the metrics provided by KEDA. The ScaledObject defines the scaling logic (e.g., which external metric to use, scaling thresholds, and min/max replicas), and KEDA takes care of managing the HPA based on this configuration.
KEDA is particularly useful for event-driven architectures where workloads may be sporadic and need scaling only when there’s an event, such as a new customer signing in or a new item being added to the cart.
KEDA supports various scalers, which are integrations with external services, such as Amazon SQS, Apache Kafka, and Prometheus. These scalers watch for changes in metrics or events, such as the number of messages in a queue or the rate of HTTP requests.
Note
Refer to the KEDA documentation at https://keda.sh/docs/latest/scalers/ for a list of available scalers.
One unique feature of KEDA is that it can scale to zero when there are no events to process, which is beneficial in serverless and event-driven applications.
To illustrate this behavior, let’s look at a sample ScaledObject configuration that enables KEDA to scale a deployment based on number of messages in an Amazon SQS queue
apiVersion: keda.sh/v1alpha1kind: ScaledObjectmetadata: name: amazonsqs-scalerspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: demo-deployment minReplicaCount: 0 maxReplicaCount: 10 pollingInterval: 15 cooldownPeriod: 180 triggers: - type: aws-sqs-queue metadata: queueURL: "http://<aws-sqs-url" awsRegion: "us-east-1" queueLength: "10" authenticationRef: name: keda-service-accountWe are defining a ScaledObject, amazonsqs-scaler, for Amazon SQS-based scaling.
minReplicaCount set to 0 defines the minimum number of replicas for the deployment. In this example, KEDA can scale the deployment down to zero, when there are no messages in the Amazon SQS queue. This helps conserve resources when there is no workload to process. maxReplicaCount set to 10 specifies the maximum number of replicas that KEDA can scale the deployment up to. This ensures that the deployment does not scale beyond 10 Pods, even if the queue size increases.
pollingInterval set to 15 makes KEDA check the queue length every 15 seconds. In this case, KEDA will query the Amazon SQS API every 15 seconds to check the size of the queue. cooldownPeriod set to 180 seconds states that after scaling up, KEDA will wait for 3 minutes before scaling down the deployment, even if the workload drops. This prevents rapid scaling down after a temporary traffic spike and allows a more stable scaling.
We are using aws-sqs-queue as the type of scaler, which is compatible with the Amazon SQS service. queueURL defines the management endpoint for the Amazon SQS service, where KEDA can query the queue depth. queueLength set to 10 defines the threshold for scaling. KEDA will trigger scaling when the number of messages in the queue exceeds 10. Lastly, keda-service-account refers to the service account that KEDA will use to authenticate with the Amazon SQS service.
Following is an example ScaledObject that automatically scales GenAI model deployments in K8s. It scales based on two triggers: the first one is based on the average number of incoming requests, and the second is based on the GPU utilization of the inference Pods. Both metrics are sourced from the local Prometheus setup, which collects these metrics from the NVIDIA DCGM exporter and the application metrics endpoint:
apiVersion: keda.sh/v1alpha1kind: ScaledObjectmetadata: name: my-llama-deployment-scalerspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: my-llama-deployment... triggers: - type: prometheus metadata: serverAddress: http://prometheus-server.default.svc:9090 metricName: http_requests_total threshold: "10" query: sum(rate(http_requests_total[1m])) - type: prometheus metadata: serverAddress: http://prometheus-server.default.svc:9090 metricName: DCGM_FI_DEV_GPU_UTIL threshold: "70" query: avg(DCGM_FI_DEV_GPU_UTIL{pod=~"my-llama-.*"}[30s])In this section, we explored the KEDA project, which brings event-driven autoscaling to K8s. KEDA extends the built-in HPA by enabling applications to scale based on custom metrics from various sources, including event-driven metrics such as message queue depth. By integrating KEDA into K8s, we can dynamically scale K8s workloads in response to external events, making resource allocation more responsive and efficient.
Cluster Autoscaler (CA)
Section titled “Cluster Autoscaler (CA)”The Kubernetes CA is a tool that adjusts the number of nodes in a Kubernetes cluster based on the needs of the workloads running in the cluster. It scales the cluster up or down by adding or removing nodes to meet the resource demands of pending or underutilized Pods.
When HPA detects that the resource usage exceeds the configured threshold, it increases the number of Pod replicas. However, if the existing nodes in the cluster don’t have enough capacity to schedule the new Pods, these Pods will remain unschedulable.
That’s where CA comes into the picture. CA detects that there are unschedulable Pods and provisions more nodes to accommodate these newly created Pods, which are unscheduled. Once the nodes are ready, the pending Pods are scheduled and start running on the new nodes.
CA supports both scale-up, when Pods are unschedulable due to insufficient resources, and scale-down; when the nodes are underutilized, the CA can remove them to optimize resource utilization and reduce costs.
CA continuously monitors the Kubernetes cluster and interacts with the cloud provider’s API to add or remove nodes based on the current resource usage. It focuses on pending Pods that cannot be scheduled due to a lack of resources and underutilized nodes that have spare capacity.
The CA identifies a node group, such as an AWS Auto Scaling Group, that is capable of provisioning additional nodes with the necessary resources. Once the new node becomes available, the pending Pods are scheduled to run on it:
- Scale-down: When nodes are underutilized, meaning they are running with low resource usage or without any significant workloads, the CA checks whether the Pods on the underutilized nodes can be safely rescheduled on other nodes in the cluster.
- Scale-up: When the application experiences high resource demand and existing nodes cannot accommodate new or pending workloads, the CA triggers scale-up. It provisions additional nodes to ensure workload scheduling. Once new nodes join the cluster, pending Pods are scheduled on them to maintain the desired performance.
While CA has been the traditional choice for scaling Kubernetes clusters, it has certain limitations, such as relying on predefined node groups and a polling-based mechanism for scaling decisions. This is where Karpenter can help. Karpenter is designed to address the inefficiencies of traditional autoscaling methods and will be covered in the next section.
Karpenter
Section titled “Karpenter”Karpenter is an open source, flexible, high-performance Kubernetes CA built by AWS. It was first introduced in 2021 during the AWS re:Invent (https://aws.amazon.com/blogs/aws/introducing-karpenter-an-open-source-high-performance-kubernetes-cluster-autoscaler/) conference, with its primary purpose to improve and simplify K8s autoscaling experience.
Unlike the native Kubernetes CA, which primarily focuses on scaling nodes in response to pending Pods, Karpenter dynamically provisions right-sized compute resources based on the specific needs of workloads. Karpenter optimizes for both efficiency and performance in the following ways:
- Faster and more efficient scaling: Karpenter can directly communicate with the Kubernetes API server to understand the pending Pod requirements and can launch new nodes faster, reducing scheduling delays. Karpenter makes these scaling decisions in near-real-time by analyzing the specific needs of pending Pods. This means that nodes are provisioned based on the immediate requirements, which reduces latency and increases responsiveness to workload changes.
- Better utilization of nodes: Unlike the CA, which typically provisions nodes from pre-configured instance groups or node pools, Karpenter can dynamically select the best instance types. It can pick instance sizes and types that match the resource requirements of the pending Pods, reducing wasted capacity and optimizing resource allocation.
- Consolidation capabilities: Karpenter continuously monitors the cluster and consolidates workloads by re-packing them onto fewer nodes when possible, terminating underutilized nodes. This consolidation helps to reduce costs by making better use of available node resources, whereas the CA generally scales down nodes based on pre-configured thresholds without aggressively consolidating workloads.
- Support for multiple instance types: Karpenter can select from a wide range of instance types, including different generations and sizes. It does this based on current availability and pricing, ensuring that Pods are scheduled on the most cost-effective and resource-appropriate nodes.
- Drift: Karpenter automatically detects the nodes that have drifted from the desired state and replaces them in a rolling manner. This functionality can be used to perform patch upgrades or K8s version upgrades of the Karpenter-managed nodes.
Karpenter looks for pending Pods in the cluster that are marked unschedulable by the kube-scheduler and aggregates the resource and scheduling requirements of those Pods to make decisions to launch new worker nodes. It performs bin-packing to ensure the correct size and number of nodes are provisioned. It also actively looks for opportunities to reduce the overall cluster costs by terminating worker nodes that are empty, under-utilized, or can be replaced with cheaper nodes, as shown in Figure 6*.3*.

Figure 6.3 – Karpenter overview
Karpenter provides two custom resources, NodePools (https://karpenter.sh/v1.4/concepts/nodepools/) and NodeClasses (https://karpenter.sh/v1.4/concepts/nodeclasses/), for configuration. NodePools define a set of provisioning constraints for the nodes created by Karpenter, such as instance types, availability zones, CPU architecture, capacity type, taints, and labels. NodeClasses configure cloud-provider-specific settings such as VPC subnets, IAM role, AMI ID, and EC2 Security groups. Multiple NodePools can be created to cater to different workload requirements, such as a GPU-specific NodePool to launch GPU worker nodes for the GenAI training and inference applications, and generic NodePools to accommodate webservers and microservices. Always ensure that NodePools are created with distinct configurations that are mutually exclusive; if multiple NodePools are matched, Karpenter will randomly pick one to launch the worker nodes.
Karpenter can be installed in the EKS cluster as a Helm chart, refer to the Getting Started guide at https://karpenter.sh/docs/getting-started/getting-started-with-karpenter/ for the instructions. In our setup, we installed the Karpenter using Terraform helm provider in Chapter 3 as part of the EKS cluster setup.
You can verify the installation using the following command, which displays the status, version, and other details of the deployment:
$ helm list -n kube-systemNAME NAMESPACE STATUSkarpenter kube-system deployedNow, let’s use the power of Karpenter to automatically launch GPU instances for our GenAI workloads. In Chapter 5, we created a dedicated EKS Managed Node group of G6 EC2 instances to deploy the Llama 3 fine-tuning job and inference applications. A disadvantage of that approach is that the GPU worker node always remains attached to the cluster, regardless of whether GenAI applications are running, which is an inefficient use of the most expensive resources. Let’s go ahead and delete the node group and configure the Karpenter to manage the GPU instance provisioning.
Comment the following code in the eks.tf file and run the Terraform commands to delete the eks-gpu-mng node group. The complete file is available at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch6/eks.tf:
module "eks" { source = "terraform-aws-modules/eks/aws" ... eks_managed_node_groups = { ... # eks-gpu-mng = { # instance_types = ["g6.2xlarge"] # ami_type = "AL2_x86_64_GPU" # max_size = 2 # desired_size = 1 # capacity_type = "SPOT" # disk_size = 100 # labels = { # "hub.jupyter.org/node-purpose" = "user" # } # taints = { # gpu = { # key = "nvidia.com/gpu" # value = "true" # effect = "NO_SCHEDULE" # } # } # } ...$ terraform plan$ terraform apply -auto-approveYou can confirm that the node group has been deleted by checking the Compute tab in EKS console or by using the following command:
$ kubectl get nodes -l nvidia.com/gpu.presentNow that we have deleted the GPU worker nodes in the cluster, let’s go ahead and configure the Karpenter by creating NodePool and EC2NodeClass resources to launch the GPU instances. Create a GPU NodePool called eks-gpu-np with a set of following requirements to pick G6 instance generation instances, from on-demand or spot capacity. The complete file is available at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch6/eks-gpu-np.yaml:
apiVersion: karpenter.sh/v1kind: NodePoolmetadata: name: eks-gpu-npspec:... nodeClassRef: group: karpenter.k8s.aws/v1 kind: EC2NodeClass name: default requirements: - key: "karpenter.k8s.aws/instance-generation" operator: In values: ["g6"] - key: "karpenter.sh/capacity-type" operator: In values: ["spot", "on-demand"] disruption: consolidationPolicy: WhenEmptyOrUnderutilized...$ kubectl apply -f eks-gpu-np.yamlnodepool.karpenter.sh/eks-gpu-np createdNext, create the default-gpu EC2NodeClass to configure the AMI, IAM role, VPC subnets, EC2 security groups, and so on. The complete file is available at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch6/eks-gpu-nc.yaml:
apiVersion: karpenter.k8s.aws/v1kind: EC2NodeClassmetadata: name: default-gpuspec: amiFamily: AL2023... role: "eks-demo"...$ kubectl apply -f eks-gpu-nc.yamlec2nodeclass.karpenter.k8s.aws/default-gpu createdNow that we have configured Karpenter, let’s rerun the fine-tuning job and see the compute autoscaling live in action. Execute the following commands to initiate the fine-tuning job. You can download the K8s manifest is available at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/llama-finetuning/llama-finetuning-job.yaml. Replace the container image, Hugging Face token, and model assets S3 bucket name values before running the commands:
$ kubectl delete job my-llama-jobjob.batch "my-llama-job" deleted$ kubectl apply -f llama-finetuning-job.yamljob.batch/my-llama-job is createdGiven that the cluster doesn’t have any GPU worker nodes, kube-scheduler will mark the fine-tuning Pod as unschedulable. We can verify that by using the following commands. The first one will output the Pending status, and the second one shows the reason for this status.
$ kubectl get pods -l app=my-llama-jobNAME READY STATUS RESTARTS AGEmy-llama-job-plgb5 0/1 Pending 0 22s$ kubectl describe pod -l app=my-llama-job | grep SchedulingWarning FailedScheduling 101s default-scheduler 0/2 nodes are available: 2 Insufficient nvidia.com/gpu. preemption: 0/2 nodes are available: 2 No preemption victims found for incoming podKarpenter is actively looking for pending Pods that are unschedulable and launches the G6 family EC2 instance in response to our fine-tuning job. Let’s verify that by looking at the Karpenter logs:
$ kubectl logs --selector app.kubernetes.io/instance=karpenter -n kube-system{"level":"INFO","time":"2025-01-31T14:34:03.899Z","logger":"controller","message":"found provisionable pod(s)","commit":"b897114","controller":"provisioner","namespace":"","name":"","reconcileID":"bbdfdd41-e86f-4cfe-8fb5-e161f3ce4a72","Pods":"default/my-llama-job-plgb5","duration":"33.662142ms"}...{"level":"INFO","time":"2025-01-31T14:36:01.277Z","logger":"controller","message":"initialized nodeclaim","commit":"b897114","controller":"nodeclaim.lifecycle","controllerGroup":"karpenter.sh","controllerKind":"NodeClaim","NodeClaim":{"name":"eks-gpu-np-gkx7t"},"namespace":"","name":"eks-gpu-np-gkx7t","reconcileID":"f2b28556-4808-4577-a559-f946a451b46c","provider-id":"aws:///us-west-2c/i-02e475780d3aed0a1","Node":{"name":"ip-10-0-32-176.us-west-2.compute.internal"},"allocatable":{"cpu":"15890m","ephemeral-storage":"95551679124","hugepages-1Gi":"0","hugepages-2Mi":"0","memory":"60398040Ki","nvidia.com/gpu":"1","pods":"234"}}Once the node has been initiated and joined the cluster, the fine-tuning job will be scheduled on it. You can verify by using the following commands:
$ kubectl get pods -l app=my-llama-jobNAME READY STATUS RESTARTS AGEmy-llama-job-plgb5 1/1 Running 0 9m20s$ kubectl get nodes -l nvidia.com/gpu.presentNAME STATUS ROLESip-10-0-32-176.us-west-2.compute.internal Ready <none>A few minutes after the job is complete, Karpenter will automatically detect the empty node, apply a taint to prevent new workloads from being scheduled, evict the existing Pods, and then terminate the node. You can verify that by checking the Karpenter logs:
$ kubectl logs --selector app.kubernetes.io/instance=karpenter -n kube-system"level":"INFO","time":"2025-01-31T14:50:18.104Z","logger":"controller","message":"tainted node","commit":"b897114","controller":"node.termination","controllerGroup":"","controllerKind":"Node","Node":{"name":"ip-10-0-32-176.us-west-2.compute.internal"},"namespace":"","name":"ip-10-0-32-176.us-west-2.compute.internal","reconcileID":"874424bd-d2f7-45ab-a399-41e5314fb3d3","taint.Key":"karpenter.sh/disrupted","taint.Value":"","taint.Effect":"NoSchedule"}{"level":"INFO","time":"2025-01-31T14:54:03.281Z","logger":"controller","message":"deleted node","commit":"b897114","controller":"node.termination","controllerGroup":"","controllerKind":"Node","Node":{"name":"ip-10-0-32-176.us-west-2.compute.internal"},"namespace":"","name":"ip-10-0-32-176.us-west-2.compute.internal","reconcileID":"eb99f292-2ea2-4aba-ac88-528746cc7e89"}In this section, we looked at the advantages of using Karpenter and installed it in the EKS cluster using Terraform and Helm. Then, we configured Karpenter to launch G6 instances for our Llama 3 fine-tuning job and inference workloads. Karpenter launched a G6 instance in response to the fine-tuning job and terminated it automatically after the job completion.
Summary
Section titled “Summary”In this chapter, we discussed scaling strategies and best practices for K8s applications to ensure efficient resource utilization and optimal performance. The chapter covers key scaling topics, including metrics, HPA, KEDA, VPA, CA, and Karpenter.
Scaling in Kubernetes involves selecting the right scaling metrics. Conventional metrics help determine the need for adding or removing Pods. Custom metrics are used for more granular control in scaling decisions.
HPA can automatically adjust the number of Pods in a deployment based on metrics such as CPU or memory usage, whereas VPA can adjust the resource requests and limits for individual Pods. VPA ensures optimal resource allocation but may conflict with HPA if both are used simultaneously.
KEDA brings event-driven autoscaling to K8s, enabling scaling based on external events such as message queue depths. It creates an HPA resource that manages scaling in response to event triggers such as spikes in API calls. KEDA can scale applications to zero, making it highly suitable for serverless and event-driven use cases. CA can adjust the number of nodes in a cluster based on Pod requirements. CA works closely with cloud provider APIs to manage nodes dynamically.
Lastly, we covered Karpenter, an alternative to CA. Karpenter can dynamically provision the right-sized compute resources to handle pending Pods. It optimizes for both performance and cost efficiency by selecting suitable instance types and terminating underutilized nodes to reduce costs. To demonstrate its functionality, we reran the Llama 3 fine-tuning job, during which Karpenter launched a node with GPU capabilities in response to the resource requirements, and automatically terminated the node once the job was complete. In the next chapter, we will discuss different strategies to optimize the overall cost of running GenAI applications on K8s.
Get This Book's PDF Version and Exclusive Extras
|