Resource Management
local graph
Chapter 17 — Resource Management
Section titled “Chapter 17 — Resource Management”In this final chapter of our book, we will cover the topic of resource management, which includes several items. The first is Pod resource limit and quota, which allows you to control your resource spend at a Pod level. We will cover how these limits are applied and enforced in a cluster. We will then work our way up the chain by covering the topic of namespace limits and quotas and will then move up another level by covering how Rancher project limits work. Finally, we will cover how to use kubecost to monitor our Kubernetes costs over time.
In this chapter, we’re going to cover the following main topics:
- How to apply resource limits and quotas to a Pod
- How namespace limits/quotas are calculated
- How to use tools such as Kubecost to track usage and cost over time
Let’s get started!
How to apply resource limits and quotas to a Pod
Section titled “How to apply resource limits and quotas to a Pod”The physical resources in a Kubernetes cluster are limited. Resources are measured based on the number of central processing unit (CPU) cores or random-access memory (RAM) allocated per worker node. For example, you might have 10 worker nodes with 4 cores per node, meaning this cluster has 40 cores available to use. This kind of cluster is acceptable until you start running out of resources. As we know, CPU and memory are not free, so we can’t just keep throwing resources at a cluster.
With Kubernetes, by default, all workloads and namespace have unlimited resources, meaning nothing stops an application from consuming all the CPU and memory in a cluster. For example, an application team could push out a new workload with a misconfigured Horizontal Pod Autoscaler (HPA) with a very high upper scale limit. It is important to note that HPAs do not allow unlimited maximum replicas, but nothing is stopping you from setting it very high. If the HPA metrics were set too low, Kubernetes starts scaling up the workload until it hits the max replica count or the cluster runs out of resources. Of course, this can cause an outage in Kubernetes clusters that are shared between environments—that is, non-production and production—or between application teams. We don’t want one application/team to cause an outage for another team.
To protect our clusters, we need to set up resource limits and quotas around our workloads and namespaces to prevent this kind of outage. We do this at two levels.
The first level is at the workload/Pod level where we want to set resource limits and requests. This applies to all workload types (deployments, statefulsets, cronjobs, daemonsets, and so on); however, limits are not applied at the workload level but at the Pod level. If I set a one core limit for deployment, that limit applies to each Pod in that deployment, meaning each Pod can consume one core. You can’t limit resources at the workload level; for example, you can’t—say—only use one core across all Pods in a workload.
Here is a YAML Ain’t Markup Language (YAML) output of a Pod with the section that we want to focus on being the resources. In that section, you’ll see that we are setting both the request and limits. In this case, we are setting a CPU request (minimum) of a quarter core with a limit (maximum) of a half core. For the memory, we are setting a request of 64 mebibytes (Mi) and a limit of 128 Mi:

Figure 18.1 – Pod resource request and limit YAML example
Looking at the preceding example, we want to focus on the resources section. In this section, we define requests and limits for this Pod. The request values are setting the required resources for this Pod. This example tells Kubernetes that the Pod needs 64 Mi of memory and a quarter core (1,000 millicores (m) = 1 core). kube-scheduler uses these values to find a node with the required available resources in the Pod scheduling process. For example, if we had a database running inside a Pod, we might set the memory request to something such as 16 gibibytes (Gi) as that is what the database will need to perform correctly. When kube-scheduler builds its list of candidate nodes, it will filter out nodes without the required resources. If a Pod requests more memory than any one node has available, it will get stuck in scheduling. It is important to note that Kubernetes will not rebalance the cluster to make room for this Pod. An unofficial tool called descheduler, found at https://github.com/kubernetes-sigs/descheduler, tries to do this. Once the Pod is scheduled on a node, kubelet will reserve the requested resources on that node.
The other part of the resource section is limits. This is where we are setting much of the resources on the node this Pod is allowed to use. For example, we might only allow this Pod to use 1 gigabyte (GB) of memory. The first setting is for the memory, which tells kubelet if this Pod uses more than the set amount of memory. It is important to note that selecting a memory limit on a Pod doesn’t change the amount of memory presented to the Pod. For example, if you set a 1 GB limit, open a shell to the Pod, and run the free -g command, you’ll see that the amount of free memory will be available to the node. If the node has 16 GB of free memory, the Pod will have 16 GB of free memory. This is why it is crucial to have memory limits on your applications and your Pod limits.
The classic example is the Java heap size because older versions of Java (before 8u191) weren’t aware of memory and CPU limits for containers. Java would overrun its memory and CPU limits simply because Java thought it had more resources available, so items such as garbage collection weren’t running to reduce memory usage. Red Hat published a great blog about this topic and went into great detail about this issue and how Java 10 added the +UseContainerSupport settings (enabled by default) to solve this problem. You can find that blog at https://developers.redhat.com/blog/2017/03/14/java-inside-docker.
But to get back to memory limits, kubelet/Docker has no way of reclaiming memory —that is, taking it back from the Pod; only the application can release used memory. kubelet/Docker can only take out of memory (OOM) action to kill a Pod. CPU limits are handled differently because if you assign one core to a Pod, that Pod can only consume one CPU’s worth. A CPU ceiling defines the maximum CPU time that a container can use. During each scheduling interval (time slice), the Linux kernel checks to see if this limit is exceeded; if so, the kernel waits before allowing that control group (cgroup) to resume execution. A cgroup is a feature of the Linux kernel that allows a parent process and its child processes to be isolated and limited in terms of the number of resources it can consume. This will show as WAIT time in programs such as top.
Kubernetes expands on limits and requests by adding quality of service (QoS) classes, which allows you to prioritize Pod evictions. If a node goes into CPU or memory pressure, kubelet will start evicting the Pod with the lowest priority first, which is the BestEffort class. This type of priority is used for Pods that are batch processing or reporting, or for other jobs that can be stopped at any time without impacting end users. The next class is Burstable, and its primary difference is that it allows the Pod to consume more resources than the defined limits, but only if a node has the available resources. Typical usage of this class is when a Pod is relatively static, such as a database, so we want to allow it to use more resources for a short period of time. However, at the same time, we don’t want to use statefulsets because doing so would mean that we can’t move around this Pod in the cluster. The other main reason is for applications that are using in-memory sessions where a Pod going down would cause disruptions. If this Pod gets evicted, the sessions are dropped, and users have to log back in. The following section will cover how namespace limits and quotas build on top of Pod requests and limits.
How namespace limits/quotas are calculated
Section titled “How namespace limits/quotas are calculated”One of the nice things about setting CPU and memory requests/limits for all Pods is that you can define namespace limits and quotas, which allows you to specify the total amount of memory and CPU used by all Pods running in a namespace. This can be very helpful when budgeting resources in your cluster; for example, if application A buys 16 CPUs and 64 GB of RAM for their production environment, you can limit their namespace to make sure they can’t consume more than what they have paid for. This, of course, can be done in two modes, with the first being a hard limit that will block all new Pod creation events for that namespace. If we go back to our earlier example, the application team has purchased 64 GB of RAM for our cluster. Suppose you have four Pods, each with a limit of 16 GB of RAM. When they try to start up a fifth Pod, it will be stuck in scheduling until the quota increases or another Pod in the namespace releases the space, with CPU limits and requests being handled in the same way.
Of course, a namespace can have both limits and requests, just as with a Pod, but it’s essential to understand how limits and requests are calculated. kube-scheduler simply adds up all limits and requests for Pods under a namespace, which means it does not use current metrics to decide if a Pod should be allowed to be scheduled in a namespace or not. It is essential to note that this only applies to hard limits. Soft limits use the metrics server to calculate currently used resources for each Pod.
The biggest issue that most people run into is allowing Pods without requests and limits into their cluster, as in the case of hard limits. Those Pods need not be a part of the calculation as their values will be zero. On the other hand, soft limits apply to all Pods as long as the metrics server runs. Because of this, it is typically recommended to set both a hard and a soft limit for your namespace.
The other important part is understanding that limits and quotas are not defined as part of the namespace definition (that is, the namespace YAML), but are defined by the ResourceQuota kind, an example of which can be found here:

Figure 18.2 – ResourceQuota YAML example with more options
However, one of the cool things is that you can set quotas on more than just CPU and memory but can also limit things such as graphics processing units (GPUs), Pods, load balancers, and so on. If you look at Figure 18.2, we specify this namespace to only allow four Pods. This is very low for most clusters/environments, but it is important to note that there is no free lunch. For example, a namespace with 100 Pods with 64 GB of total memory and another namespace with only four Pods using the same amount of memory are two different workloads. The 100 Pods put a much larger workload on the node and cluster management services than just four Pods. The same is true with a namespace that stores a lot of data in the form of secrets versus configmaps as a secret is customarily encrypted and stored in memory on the kube-apiservers. Because they are encrypted, they tend to be uncompressible, as opposed to configmaps, which are stored in plain text and are generally compressible. The other common limit users put on a namespace is a load balancer. In many cloud environments, when you deploy a load balancer in Kubernetes, you are typically deploying a load balancer in the cloud provider, which costs money.
Note
This covers a Layer-4 load balancer and not an ingress, which is usually a shared resource.
One of the nice things about Rancher is it builds on top of namespace limits and quotas by allowing you to define project-level limits and requests. This will enable you to define limits for a team that might have multiple namespaces. A classic example is a non-production cluster where an application team might buy X amount of CPU and RAM and then choose how to distribute it across environments.
For instance, they might assign half of it to DEV and QAS most of the time, but during load testing, they might want to spin down their DEV and QAS namespaces to shift those resources to their TEST namespace and then back, after their testing is done. As a cluster administrator, you don’t care about nor need to make any changes as long as they stand under their project limits. It is important to note that projects are Rancher objects because the downstream cluster has no idea what a project is. Rancher controls projects and uses namespace labels, annotations, and Rancher controllers to synchronize settings between Rancher and the downstream cluster.
In the next section, we will cover using tools such as Kubecost to build on top of resource quotas to allow you to do things such as show back and charge back to recover costs in your cluster.
How to use tools such as Kubecost to track usage and cost over time
Section titled “How to use tools such as Kubecost to track usage and cost over time”One of the essential things about Kubernetes is it enables application teams to move fast and consume resources with very few limits by default. This means that many environments early on in their Kubernetes journey tend to have a lot of spending. The perfect example is what is covered in Chapter 13, Scaling in Kubernetes, allowing you to auto-scale both your cluster and workloads. This means an application team can make a change that increases your costs by a significant number without you knowing until the bill comes, and now you have to go back and find out what changed, and—of course—it becomes tough to pull back resources after Kubernetes has been used for some time.
We can address this issue by using Kubecost, an open source cost monitoring, and reporting tool. Note there is a free community edition and a paid commercial product that expands on the open source project. Kubecost connects your cloud provider—such as Amazon Web Services (AWS), Azure, or Google Cloud Platform (GCP)—to get the current cost of your resources, then ties that cost to the Pods consuming it in the cluster. For example, you use the latest and greatest CPU on some nodes with old CPU (cheaper) versions on other nodes. Kubecost allows you to tie the different costs back to the Pod. Because of this, you can choose to switch to newer high-performance CPUs as your applications/Pods run better on them and use fewer resources than slower CPUs.
Kubecost is deployed using a Helm chart or a YAML manifest inside the monitoring cluster. Currently, Kubecost doesn’t support remote monitoring, meaning it must be deployed on each cluster in your environment. In addition, Kubecost uses Prometheus to collect metrics in your cluster that can be deployed as part of the Helm chart; the same applies to Grafana for presenting dashboards. Kubecost has its own network metrics collector for collecting traffic costs for different kinds of traffic; for example, some cloud providers charge you more for traffic outside your region than local traffic. The highest price is for egressing out to the public internet, which can be very expensive. The saying is that AWS wants you to bring data into their environment at little to no cost but will charge you an arm and leg to get it back out.
The steps can be as simple as executing the helm install command with a token that ties your install to your Kubecost account for installing Kubecost, an example of which you can find in the following screenshot. A complete list of Helm chart options can be found at https://github.com/kubecost/cost-analyzer-helm-chart/blob/master/README.md#config-options. These options allow you to customize your deployment:

Figure 18.3 – ResourceQuota YAML example with more options
In the preceding example, we install Kubecost with the default settings, which will deploy its own instances of Prometheus, Node Exporter, and Grafana. It is highly recommended to reuse your current Rancher monitoring version 2 (v2) deployment as the two will conflict. This is done by setting the global.prometheus.enabled=false, prometheus.kube-state-metrics.disabled=true, and prometheus.nodeExporter.enabled=true options. I would also recommend reading through the Kubecost documentation at https://guide.kubecost.com, which includes adding external resources such as Simple Storage Service (S3) and Relational Database Service (RDS). In addition, their guide walks you through the steps needed to allow Kubecost to query your billing information for any custom pricing; for example, larger AWS customers can get a disconnect on their accounts for some resource types.
Finally, Kubecost has an experimental hosted offering, which can be found at https://guide.kubecost.com/hc/en-us/articles/4425132038167-Installing-Agent-for-Hosted-Kubecost-Alpha-. Also, Kubecost is not the only player in town as products such as Datadog can provide cost monitoring and reporting. The essential item is that we want to track our costs over time to know when something changes, and—of course—because we understand how much each Pod costs, we can create reports for management to show where the money is going so that they can turn around and go after application teams to pay for their resources. We do this to budget our information technology (IT) spending, allowing us to be proactive instead of reactive.
Summary
Section titled “Summary”This chapter went over what Pod limits and requests are and how they are enforced by Kubernetes, including how they are calculated. We then covered how to use resource quotas at the namespace level to limit these to the team/application level, as well as limiting other resources such as load balancers, secrets, and so on. We then worked our way up the chain by covering the topic of Rancher projects, allowing us to set limits across a namespace. Finally, we covered how to use Kubecost to monitor our Kubernetes costs over time, including how to install and customize it, but more importantly, we covered why we want to monitor and track our costs over time. In addition, we covered some additional solutions such as Datadog.
The journey we have undertaken together is coming to a close. I want to congratulate you on finishing this book, as well as thank you for taking the time to learn about Rancher and Kubernetes. My final note is to remember that Rancher and Kubernetes are an ever-evolving ecosystem. It would be best if you always kept learning more, with Rancher’s official events being an excellent resource for learning about new features in both Rancher and Kubernetes. You can find out more about this at https://rancher.com/events.