# Kubernetes recommendations

> How LevelFour sizes container requests, keeps room for the JVM heap and your namespace limits, works with HPA, KEDA and VPA, changes NodePools, node groups and volume claims, checks every change once it lands, and measures what it saved on your bill.

Source: https://docs.levelfour.ai/kubernetes/recommendations


LevelFour recommends CPU and memory requests for the containers in the namespaces you opted in, Jobs and CronJobs included, and HPA minimums and targets. It also recommends changes to Karpenter NodePools and managed node groups, and smaller PersistentVolumeClaims. Each recommendation arrives on the **Savings** page like any other. You approve a container, NodePool or node group change as a pull request on your own repository, and run a claim resize yourself. The optional [automation component](/kubernetes/automation) can merge the safest of these pull requests for you, and fix OOM kills and CPU throttling on running pods.

## How a request is sized

A recommendation starts from what the container used over the last 14 days, hour by hour, and adds headroom on top. A [RecommendationsConfig object](#set-the-policy-with-objects-in-the-cluster) can set a window of 1 to 30 days instead. CPU is sized from its p99, memory from its peak, and neither goes below what the container needs while it starts. Containers built on runtimes that hold memory up front, such as the JVM and .NET, get more headroom than others.

### JVM heap

A JVM can grow its heap to its maximum at any time. When `-Xmx` sets that maximum where the agent can read it, the JVM's memory request never drops below it plus the memory the JVM uses outside the heap: 256 MiB plus a tenth of the heap. That floor only holds a cut back. A request already under it stays where it is, and a raise still needs the usage to ask for it. [What the agent reads](/kubernetes/agent-permissions-and-data#what-it-sends) lists where it looks.

A JVM whose heap the agent cannot read gets no memory cut, since its image may let the heap grow past anything it used so far. That covers a heap set as a share of the memory limit, the JVM's default, options set by the image, and options from a ConfigMap or a Secret. A JVM with no CPU limit keeps its CPU request, because older JDKs count their processors from it. Once LevelFour trusts a [measured heap](#the-measured-heap), it can lift either hold. The workload drawer's **Spec** section shows each container's heap and the floor it sets.

### The measured heap

With the [JVM reader](/kubernetes/agent-permissions-and-data#the-jvm-reader) on, LevelFour also reads each JVM's heap from the running JVM: the heap it may grow to, the most memory it used beside the heap, an upper bound on its live set, its time in garbage collection pauses and its JDK version. Several JVMs in one container add up. The workload drawer shows what the reader measured in each container, day by day.

> **Note: Shadow until LevelFour turns it on**
>
> The measured heap starts off for every organization, and sizes nothing until LevelFour turns it on for yours. Until then it runs in shadow: LevelFour keeps the measurement beside each recommendation and sizes the JVM from its spec alone, as above. Before it turns the measured heap on, LevelFour checks the measurements against the `-Xmx` your specs set.

Even in shadow, a container the reader found a JVM in counts as a JVM, whatever its image is called: its limits never go down, it gets no memory cut unless the spec fixes its heap, and with no CPU limit it keeps its CPU request.

#### Three heap classes

LevelFour puts each JVM's heap in one of three classes:

| Class                 | When                                                                                                                                                                                                                   | What a trusted measurement adds                                                                     |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| **Fixed**             | The spec shows `-Xmx` where the agent can read it. A `-Xmx` the reader finds only in the running JVM does not count, because a start script may have worked it out from the memory limit                               | A higher memory floor, when the JVM uses more beside the heap than the spec's floor leaves room for |
| **Follows the limit** | The JVM sizes its heap from the container's memory limit: a share of it, the JVM's default, or options the image sets                                                                                                  | A memory cut, down to the measured floor. The limit stays, so the heap keeps its size               |
| **Follows the node**  | The JVM cannot see a memory limit: the container has none in its spec or in its running pods, the JVM runs with `-XX:-UseContainerSupport` or `MaxRAM`, or its JDK did not report its version or cannot read cgroup v2 | Nothing. LevelFour never trusts the measurement, and the JVM keeps its memory request               |

JDK 15 and later read cgroup v2, and so do JDK 8 from 8u372 and JDK 11 from 11.0.16. LevelFour does not know which cgroup version a node runs, so it takes an older JDK to be on cgroup v2, where it cannot see its limit.

#### When LevelFour trusts a measurement

A measurement sizes the container only when all of these hold:

* LevelFour turned the measured heap on for your organization.
* The heap is fixed or follows the limit.
* The reader measured the container's JVMs for at least 72 hours of its sizing window, and the newest of those hours is at most 3 hours old.
* The reader measured at least 90% of the time the agent saw the container, from the first hour it measured a JVM there.
* No JVM in the container went unread in the window, for any reason but still starting.
* The reader read the JVM's record of its options whole.
* No hour put the heap above the memory limit the pods ran with. No JVM can grow its heap past its container's limit, so LevelFour does not trust a measurement that says one did.

An hour counts only when the agent saw the container in it, after the pod template's requests or limits last changed, with the pods at the memory limit the template and the running pods hold today. A JVM sizes its heap from the limit it starts with, so an hour at another limit measured another heap.

#### The memory floor

A trusted measurement sets a memory floor: the heap the JVMs may grow to, plus room beside it. The room is 256 MiB and a tenth of the heap, or a fifth more than the most the JVMs used beside the heap, whichever is larger. When the spec also fixes the heap, the larger of the two floors holds.

The measured floor works as the spec's does. It holds a cut back, a request already under it stays where it is, and a raise still needs the usage to ask for it. After OOM kills on a heap that follows the limit, the raised limit brings a larger heap, so LevelFour sizes the raise to keep the measured room beside that larger heap.

When the measured floor decides the memory a change asks for, the recommendation says so.

#### Holds

* **Pressure holds every cut.** When a trusted measurement shows a JVM spending more than a tenth of any span of 5 minutes or more in garbage collection pauses, or heap in use that never fell below 70% of the heap it may grow to during an hour, even after collections, LevelFour holds every cut on the container, CPU and memory. ZGC and Shenandoah count no pause share, so only the 70% rule applies to them.
* **Limits never go down.** A measurement shows the heap at today's limit only, so a lower limit would still be a guess at the heap and the collector the JVM picks from it.
* **No auto-merge.** A cut on a container whose measurement LevelFour trusts never merges on its own, whatever [auto-merge](/kubernetes/automation#auto-merge) classes its namespace allows.

#### The CPU request by JDK version

With no CPU limit, older JDKs count their processors from the CPU request, so a JVM with no CPU limit keeps its CPU request. JDK 19 and later count processors from the node instead, and so do JDK 11 from 11.0.17 and JDK 17 from 17.0.5, so a lower request leaves the JVM as it is. When a trusted measurement shows one of those, LevelFour lifts the hold and sizes the CPU request like any other. Across the window, the oldest JDK the reader saw decides.

### Namespace limits

Recommendations stay inside each namespace's LimitRange and ResourceQuota, so Kubernetes accepts the new pods:

* **LimitRange.** No request or limit goes below the minimum or above the maximum. A cut keeps the container's limits, so the request stays at or above each limit divided by the maximum limit-to-request ratio.
* **ResourceQuota.** A raise, such as more memory after OOM kills, fits in what the quota has left. When the quota caps it, the recommendation says so.

The namespace page lists its quotas, with what is used against each hard value, and its LimitRanges.

### Jobs and CronJobs

A Job's pods run for minutes and stop, so LevelFour sizes a Job or a CronJob from everything its runs used, start to finish, across the runs it saw. It waits until it has seen runs on enough days, as it waits for any container. The pull request edits the Job's pod template, under `spec.jobTemplate` for a CronJob.

### Sizing policies

A sizing policy sets how much room a namespace or a workload keeps. Set it on the namespace page, or on one workload from its drawer. A workload's policy wins over its namespace's.

| Policy                 | CPU                                   | Memory                                 | Use it for                                                      |
| ---------------------- | ------------------------------------- | -------------------------------------- | --------------------------------------------------------------- |
| **Maximum savings**    | p95, with the least headroom          | Peak, with the least headroom          | Batch jobs and workloads that tolerate a little throttling      |
| **Balanced** (default) | p99, headroom from how spiky usage is | Peak, headroom from how spiky usage is | Most services                                                   |
| **Extra headroom**     | Balanced plus 15 points               | Balanced plus 15 points                | Latency-sensitive services and anything that recently regressed |

A change applies from the next scan. A recommendation already published keeps the sizing it had. Admins and members can change a policy; viewers see it.

### Set the policy with objects in the cluster

With the [automation component](/kubernetes/automation) installed, you can set the sizing policy in the cluster instead, with a `ClusterRecommendationsConfig`, `NamespaceRecommendationsConfig` or `WorkloadRecommendationsConfig` object. [The sizing policy](/kubernetes/automation#the-sizing-policy) shows one. An object wins over the policy set in LevelFour, and the most specific object wins. The objects shape recommendations whether or not automation is turned on, and they offer four settings the dashboard does not:

* **MaxHeadroom:** Balanced plus 30 points, up to 80% headroom, for the services that need the most room.
* **cpuPolicy** and **memoryPolicy:** a policy for each resource on its own.
* **customTimeWindowDays:** the days of usage a recommendation reads, from 1 to 90. With automation on, a container takes no step before it has that many days.
* **memoryRequestEqualsLimit:** the memory limit moves to the recommended memory request, so the two stay equal. A JVM's memory limit never goes down this way: its request moves and its limit stays.

A field no object sets keeps the policy set in LevelFour, or its default. A regression still lifts a container to at least **Extra headroom** for 30 days.

## HPA, KEDA and VPA

**HPA and KEDA.** When an autoscaler scales on CPU or memory utilization, lowering the request would make it scale earlier. LevelFour changes the target with the request, in the same pull request, so the autoscaler keeps firing at the same real usage. When the new target would land outside 1 to 90 percent, LevelFour skips that resource. A target set as an average value is independent of the request, so the request changes alone.

**HPA minimum and target.** LevelFour also recommends changes to the HPA itself:

* **A lower `minReplicas`**, when the HPA sits at its minimum in at least 90% of the hours and its pods use less than half of the target there. The extra replicas are what you pay for.
* **A higher CPU target**, 70%, when the HPA scales on CPU utilization with a target under 50% and its pods are never throttled.

Each one arrives as its own pull request on the HPA.

**VPA.** A VPA in `Auto`, `Recreate`, `Initial` or `InPlaceOrRecreate` mode writes the requests it controls, so LevelFour leaves those alone. Its container policy decides which: a container set to `mode: Off`, or a resource left out of `controlledResources`, still gets a recommendation. A VPA in `Off` mode only recommends, so the workload gets a recommendation, with the VPA's own target shown beside it.

## NodePools, node groups and claims

A NodePool or node group change covers every workload on the pool, so it does not wait for namespace opt-in. [Node optimization](/kubernetes/nodes#nodepool-and-node-group-recommendations) explains how LevelFour picks each change and prices it.

| Recommendation   | What it changes                                              | How you apply it                                                                                                                                                                                                               |
| ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **NodePool**     | The NodePool's `requirements` and `spec.disruption` settings | Merge the pull request on the source that deploys the NodePool: an Argo CD application, a Helm release or a manifest in your repository                                                                                        |
| **Node group**   | `instance_types` and `capacity_type` of a managed node group | Merge the pull request on the Terraform that defines the group                                                                                                                                                                 |
| **Claim resize** | A PersistentVolumeClaim's size                               | **Manual Setup**: create a smaller claim and copy the data across, following the steps in the recommendation. [PersistentVolumeClaim resize](/kubernetes/nodes#persistentvolumeclaim-resize) explains why it takes a new claim |

## After you merge

LevelFour watches every merged change in your cluster. For a container:

1. **Rolled out.** The cluster runs the new requests.
2. **Verified** or **Regressed.** A day later, LevelFour compares OOM kills, restarts and CPU throttling against the week before. More of any of them is a regression.
3. **Reverted.** After a regression, LevelFour opens a pull request that puts the old values back. Once the cluster runs them, the next recommendation for that container uses **Extra headroom** for 30 days, whatever its policy.

LevelFour marks a change as never applied when its pull request closes unmerged, or when nothing rolls it out within 30 days.

A change that regressed, was reverted or never applied keeps its logs on the saving and offers no **Retry**. The next change for that container arrives as a new recommendation.

The workload drawer shows each step on its timeline, next to the pull request that opened and merged it.

For the other kinds, LevelFour reads what the cluster runs:

* **NodePool:** rolled out once the NodePool in the cluster carries the recommended fields.
* **Node group:** rolled out once every node in the group runs a recommended instance type on the recommended capacity type.
* **Claim resize:** verified once the workload mounts a new claim, created after the recommendation, at or under the new size. A resize has nothing left to regress, so it skips the day-later check.

A day after a NodePool or node group change rolls out, LevelFour checks the workloads with pods on the pool against the week before. Evictions at a higher rate, or pods waiting to be scheduled for at least 10 minutes in total at more than twice the rate, mark it **Regressed**. It reads **Reverted** once the pool's old settings are back in the cluster.

## Realized savings

A week after a verified rollout, LevelFour compares what the container cost the week before and the week after, from your bill, and records the difference as realized savings on **Savings Audit**. A scale-to-zero or a deleted volume saves what it cost before. For a NodePool or node group, LevelFour compares the cost of the pool's nodes, and for a claim resize, the cost of its volume.

> **Note**
>
> A lower request cuts the container's share of the bill at once. Your node bill drops when nodes consolidate and fewer of them run, so it can trail the realized figure by a few days.

## Signals on the Kubernetes pages

**Suspected memory leak.** Memory climbs in a steady line between restarts, by at least 20 percent over at least a day. LevelFour holds back any memory cut for that container, because its peak only says how far it got before it restarted.

**CPU runaway.** CPU climbs in a steady line with no restart, by at least 50 percent over at least a day.

**GPU.** When Prometheus scrapes NVIDIA's DCGM exporter, each container shows GPU utilization and GPU memory used against what its GPUs hold. [Configuration](/kubernetes/configuration) has the setup.

**Health score.** The fleet table scores each cluster from 0 to 100. Efficiency, the share of container cost not wasted, counts 40 percent. Reliability, the share of workloads not at risk with a medium risk counting half a high one, counts 40 percent. Hygiene, the share of containers with CPU and memory requests and a memory limit, counts 20 percent. Hover the score to see each part.

**Workloads at risk.** The **Reliability** tab's **Workloads** list opens on **At risk**: the workloads at high risk now, the worst first. LevelFour ranks them by restarts plus evictions in the window, then OOM kills, then the time their pods spent Pending, then how many indicators raise their risk.

**CO2 estimate.** The fleet table and the cluster page estimate each cluster's operational emissions over the date range, with [Cloud Carbon Footprint](https://www.cloudcarbonfootprint.org/docs/methodology/)'s method and its published coefficients: compute energy from each node's vCPU hours at the CPU use the agent measured (50 percent where none was), plus memory energy, times the cloud's power usage effectiveness and the region's grid emission factor. A node type whose CPU LevelFour cannot place uses its cloud's average for that CPU. The estimate leaves out the emissions of building the hardware. A cluster with no cloud, or in a region with no published grid factor, gets no estimate.

**Compare two periods.** Turn on **Compare** next to the date range on a cluster page to see cost, efficiency and waste for two periods side by side.

**Group by a virtual tag.** The cost views group by any [virtual tag](/virtual-tags#kubernetes-in-a-tag) that has Kubernetes rules. A tag whose rules pick clusters and namespaces works as an allocation group: one value can sum namespaces from several clusters.

**Save a report.** **Save report** on a Kubernetes cost view keeps its grouping, metric and cluster. Open it again from **Reports** and read it by day, by week (Monday to Sunday) or by month. A period the date range cuts is marked partial.

## Alerts and the weekly summary

[Cost alerts](/cost-alerts) can watch a cluster, a namespace or a workload: its cost or its waste against a budget, or its reliability at a minimum risk, posting in your Slack channels. A reliability alert can send each namespace to its own channels, as [Kubernetes alerts](/cost-alerts#kubernetes-alerts) explains, and any alert can also reach [Datadog](/cost-alerts#where-alerts-arrive) as an event. Switch on the **Kubernetes** group in [notification preferences](/notifications) to get a summary every Monday with each cluster's cost and unused spend, per namespace. It starts off.
