Most clusters request far more CPU and memory than they use, and the bill is for the requests, not the use. Rightsizing fixes that, and it is also an easy way to cause an outage: lower a memory request below a weekly peak and pods are OOMKilled on Monday morning; lower a CPU request under an HPA and the autoscaler adds replicas, so the bill goes up. This capstone builds a read-only rightsizing workflow: pull usage from Prometheus, check the evidence is good enough to act on, compute recommendations with headroom, catch throttling, OOMKills, and autoscaler interactions, estimate the saving, and hand each team a reviewed pull request instead of changing anything yourself.
Difficulty: Master · Know this first: Lesson 100, Lesson 152, Lesson 167
This bar splits one rightsizing pass, in hours. It is a worked example, not a measurement. The analysis is a few hours; the review and the watching afterwards are most of the time, on purpose.
Set a container's p95 CPU usage, its current and proposed requests, the HPA target, and the replicas it runs today. See what the HPA would do after the change.
utilization = usage ÷ request · HPA wants ceil(replicas × utilization ÷ target), never fewer than today's minimum here · CPU requested = replicas × request
Saves CPU, but the HPA adds a replica
Three questions. No score is saved anywhere — this is just you against the material.
This capstone grows in four levels: first why requests cost money, then the queries and the arithmetic, then the safety checks, and finally a recurring rightsizing programme across teams.
At the basic level you know that the scheduler packs pods by requests, so nodes fill up by requests, and you pay for nodes. A pod that requests 1 core and uses 0.2 still occupies a whole core of node capacity. Rightsizing brings requests close to real use plus headroom.
Terms: request, limit, usage, working set, p95, headroom, throttling, OOMKill, bin packing, consolidation.
Where it breaks: cutting memory to the average; the next peak kills the pod.
Try it: Basic
Why does an over-sized CPU request cost money even when the CPU is idle?
Now do it: Run rightsize.py in Go deeper and read which containers get no recommendation, and why.
At the intermediate level you write the queries and the rules.
rate(container_cpu_usage_seconds_total[5m]) over 14 days, per container; request ≈ p95 × 1.15, rounded to 50m.container_memory_working_set_bytes over 14 days; request ≈ peak × 1.2, rounded; limit equal to or a little above.container_cpu_cfs_throttled_periods_total ÷ container_cpu_cfs_periods_total.kube_pod_container_resource_requests and limits from kube-state-metrics.Try it: Intermediate
Which memory metric should you size requests from?
Now do it: Run the PromQL in Go deeper against a Prometheus you can read, for one namespace.
At the advanced level the checks matter more than the arithmetic.
Try it: Advanced
A Java service's heap is set to 75 percent of its memory limit by the JVM. You lower the limit by 40 percent. What else changes?
Now do it: For one workload, list what reads its requests and limits: the scheduler, the HPA, the runtime, and quotas.
At the master level rightsizing is a monthly practice, not a one-off project.
Trade-off: tight requests save money and leave less room for surprises; generous ones are safe and expensive. Headroom is a decision, written down per service.
Try it: Master
A tool suggests cutting every request by 60 percent across the cluster tonight. What do you do?
Now do it: Design the monthly job: its query, its checks, and the pull request it opens.
The whole workflow, minus Prometheus, fits in one script: evidence checks first, then CPU from p95 with headroom, memory from the peak, and the throttling, OOMKill, and HPA rules. The rows stand in for what the queries below return. Standard library only; python3 rightsize.py.
# rightsize.py - read-only rightsizing from metrics, with evidence checks before any recommendation
import math
# One row per container, as the PromQL in this lesson would return it over the window.
# cpu_* in millicores, mem_* in MiB; coverage = share of expected samples present.
rows = [
# name, days, coverage, cpu_req, cpu_p95, throttled, mem_req, mem_max, oomkills, hpa_target
("checkout", 14, 0.99, 1000, 310, 0.01, 1024, 610, 0, None),
("search", 14, 0.97, 500, 470, 0.18, 512, 480, 0, None),
("reports", 2, 1.00, 2000, 150, 0.00, 4096, 900, 0, None),
("api", 14, 0.98, 800, 280, 0.02, 512, 300, 0, 70),
("worker", 14, 0.62, 1000, 200, 0.00, 2048, 700, 0, None),
]
CPU_HEAD, MEM_HEAD = 1.15, 1.20 # headroom over p95 CPU and over peak memory
def evidence(days, coverage):
if days < 7:
return "insufficient: under 7 days, weekly peaks not seen"
if coverage < 0.9:
return f"insufficient: only {coverage:.0%} of samples present"
return None
print(f"{'container':<10} {'cpu req -> rec':>15} {'mem req -> rec':>16} note")
for name, days, cov, creq, p95, thr, mreq, mmax, ooms, hpa in rows:
why = evidence(days, cov)
if why:
print(f"{name:<10} {'-':>15} {'-':>16} no change: {why}")
continue
cpu_rec = max(50, math.ceil(p95 * CPU_HEAD / 50) * 50)
mem_rec = max(64, math.ceil(mmax * MEM_HEAD / 64) * 64)
note = []
if thr > 0.05:
cpu_rec = max(cpu_rec, creq)
note.append(f"throttled in {thr:.0%} of periods: it needs more CPU, not less; raise the request and review the limit")
if ooms:
mem_rec = max(mem_rec, mreq)
note.append("OOMKilled recently: do not lower memory")
if hpa and cpu_rec < creq:
util_now = p95 / creq * 100
util_new = p95 / cpu_rec * 100
note.append(f"HPA targets {hpa}% of the request: utilization would read {util_new:.0f}% instead of"
f" {util_now:.0f}%, above target, so it would add replicas; change request and target together")
print(f"{name:<10} {creq:>6}m -> {cpu_rec:>5}m {mreq:>6}Mi -> {mem_rec:>5}Mi {'; '.join(note) or 'safe to propose'}")
$ python3 rightsize.py container cpu req -> rec mem req -> rec note checkout 1000m -> 400m 1024Mi -> 768Mi safe to propose search 500m -> 550m 512Mi -> 576Mi throttled in 18% of periods: it needs more CPU, not less; raise the request and review the limit reports - - no change: insufficient: under 7 days, weekly peaks not seen api 800m -> 350m 512Mi -> 384Mi HPA targets 70% of the request: utilization would read 80% instead of 35%, above target, so it would add replicas; change request and target together worker - - no change: insufficient: only 62% of samples present
Read it like this: checkout is safe to propose; search is throttled, so it gets more CPU; reports and worker get no recommendation at all because their evidence is too thin; and api's numbers look like a saving until the HPA note says the autoscaler would add replicas.
# p95 CPU per container, in cores
quantile_over_time(0.95, (sum by (namespace, pod, container) (rate(container_cpu_usage_seconds_total{namespace="shop", container!=""}[5m])))[14d:5m])
# peak working-set memory per container, in bytes
max_over_time((max by (namespace, pod, container) (container_memory_working_set_bytes{namespace="shop", container!=""}))[14d:5m])
# share of CFS periods throttled, per container
sum by (namespace, pod, container) (increase(container_cpu_cfs_throttled_periods_total{namespace="shop"}[14d]))
/ sum by (namespace, pod, container) (increase(container_cpu_cfs_periods_total{namespace="shop"}[14d]))
# current requests (kube-state-metrics)
kube_pod_container_resource_requests{namespace="shop", resource=~"cpu|memory"}
# OOMKills in the window
sum by (namespace, pod, container) (increase(kube_pod_container_status_restarts_total{namespace="shop"}[14d]))
and on (namespace, pod, container) kube_pod_container_status_last_terminated_reason{reason="OOMKilled"} == 1
These are read-only queries; subqueries over 14 days are heavy, so run them off-peak or against recording rules. Aggregate per workload (Deployment or StatefulSet) rather than per pod before recommending, because pods come and go within the window. Metric names follow cAdvisor and kube-state-metrics; check them against your exporters.
This is a composite of a failure pattern that keeps repeating; the numbers are illustrative. A cost initiative applied a vendor tool's recommendations to every namespace on a Thursday.
Rightsizing became a read-only monthly job with a 14-day minimum window, coverage checks, OOMKill and throttling rules, an HPA check, and per-team pull requests reviewed by owners. The saving was smaller and real, and there were no incidents in the following year.
Build a monthly rightsizing programme for a 400-node cluster shared by 30 teams, where requests are about three times actual usage.
Which workloads have HPAs or VPAs? How long is Prometheus retention, and is it complete? Which teams have seasonal peaks? Can the node autoscaler consolidate? Who approves changes, and how fast must they answer?
Say 4,000 containers, 15-day retention at 30-second resolution, 60 percent of workloads without HPAs, and on-demand nodes at a known price per core-hour.
A scheduled read-only job using recording rules for p95 CPU, peak working set, throttling, and OOMKills over 14 days; evidence checks per container; recommendations with headroom per service tier; HPA-aware rules; per-team pull requests with the evidence and a cost range; owner approval within a week; one workload at a time with 48 hours of watching; LimitRanges and quotas to stop drift; showback of requested versus used cost; and a monthly report of savings and incidents.
Automated pull requests scale to 30 teams and need trust in the evidence; owner review slows savings and prevents incidents. Smaller headroom saves more and leaves less room for unknown peaks. Leaving autoscaled workloads to their HPAs is simpler and may leave money on the table; moving requests and targets together captures it with more care.