Platform Engineering · Lesson 194

Capstone: Rightsize a Kubernetes Cluster from Prometheus Metrics

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

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: a smaller request under an HPA

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

80%utilization after
5replicas the HPA wants
-1.45cores requested, change

Saves CPU, but the HPA adds a replica

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

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.

Basic — Why requests are the bill

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.

Intermediate — The queries and the arithmetic

At the intermediate level you write the queries and the rules.

  • CPU: p95 of rate(container_cpu_usage_seconds_total[5m]) over 14 days, per container; request ≈ p95 × 1.15, rounded to 50m.
  • Memory: max of container_memory_working_set_bytes over 14 days; request ≈ peak × 1.2, rounded; limit equal to or a little above.
  • Throttling: container_cpu_cfs_throttled_periods_total ÷ container_cpu_cfs_periods_total.
  • Current settings: 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.

Advanced — Safety checks before any proposal

At the advanced level the checks matter more than the arithmetic.

  • Evidence: at least 7 days (14 better), 90 percent sample coverage, no deploy in the window that changed behaviour, known seasonal peaks noted.
  • Throttling: throttled containers get more CPU; review CPU limits.
  • OOMKills: never lower memory after one; investigate leaks first.
  • Autoscalers: HPA targets move with requests; VPA in Auto mode owns the workload's requests already.
  • JVM and runtimes: heap settings derived from limits change when limits change; check them.
  • Savings: only real if nodes scale down; check the node autoscaler or consolidation.

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.

Master — A recurring programme

At the master level rightsizing is a monthly practice, not a one-off project.

  • Pipeline: a scheduled read-only job runs the analysis and opens pull requests per team with evidence attached; owners merge or decline with a reason.
  • Guardrails: LimitRanges for defaults, ResourceQuotas per namespace, and admission policy requiring requests on every container.
  • Showback: requested versus used cost per team, so the incentive is visible.
  • Tools: VPA in recommendation mode, Goldilocks, OpenCost, and commercial tools produce similar numbers; the evidence checks and the owner review are what make them safe.
  • Measure: requested-to-used ratio per cluster over time, incidents caused by rightsizing (target zero), and node count.

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.

Go deeper

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.

Recommendations, with the reasons not to

# 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.

The PromQL behind each column (14-day window)

# 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.

One time it broke

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.

Timeline

  • ThursdayRequests drop 50 percent across 300 workloads. The node count falls by a third over the night. The dashboard shows a large saving.
  • Monday 06:00The weekly settlement batch starts. Its memory peak, not seen in the tool's 4-day window, exceeds the new limits; pods are OOMKilled in a loop.
  • Monday 09:00The API's HPA has scaled from 6 to 14 replicas since Thursday, because its utilization doubled on paper. Its cost is higher than before the change.

What changed after

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.

If you remember nothing else

Design exercise

Build a monthly rightsizing programme for a 400-node cluster shared by 30 teams, where requests are about three times actual usage.

Clarifying questions to ask

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?

Rough sizing

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.

Shape of the answer

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.

Trade-offs to name

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.

Saved on this device, in this browser.
Next in this series · Lesson 195
Capstone: Build a Kafka Streaming Platform on Kubernetes with Strimzi

Running one Kafka cluster is a lesson; offering Kafka to a dozen teams is a platform. This capstone builds that platform on Kubernetes with Strimzi: size it from the peak, declare the cluster, topics, and users as code, add a…

Go to Lesson 195 →

Or browse the full course from the Lessons index.