How-To Guide

Rightsizing Kubernetes CPU and Memory Requests

Set Kubernetes CPU and memory requests and limits to prevent CFS throttling and OOMKill loops while hitting Guaranteed or Burstable QoS targets.

On this page

  1. Why Guesswork Resource Specs Break Both Cost and Latency
  2. How Kubernetes QoS Classes and Node Allocatable Work
  3. Production Deployment Manifest with Runtime Alignment
  4. Prometheus Queries for Telemetry-Driven Rightsizing
  5. Common Sizing Mistakes and Cluster Traps
  6. Verifying Capacity Fit and Runtime Stability

Why Guesswork Resource Specs Break Both Cost and Latency

Every Kubernetes outage involving OOMKilled (Exit Code 137) or mysterious 400ms API latency spikes usually traces back to arbitrary numbers copy-pasted inside resources.requests and resources.limits. Developers routinely request 50m CPU and 128Mi memory “just to fit on dev nodes”, or copy limits.cpu: "500m" onto every microservice without realizing how the Linux Completely Fair Scheduler (CFS) enforces CPU quotas in 100-millisecond slices.

CPU and memory behave fundamentally differently under pressure. CPU is compressible: when a node gets busy, pods still receive at least their requests.cpu weight and slow down proportionally without dying. Memory is incompressible: once a container allocates a byte beyond its limits.memory, the Linux kernel’s Out-Of-Memory (OOM) killer immediately terminates the process (SIGKILL), dropping all in-flight HTTP connections.

Before generating deployment YAML, you can calculate per-pod millicores, memory headroom, cluster-wide totals, and node bin-packing fit interactively in the Interactive Kubernetes Resource Calculator.

How Kubernetes QoS Classes and Node Allocatable Work

Kubelet assigns every pod one of three Quality of Service (QoS) classes that dictate scheduling and eviction priority when a node runs low on memory:

  1. Guaranteed: Every container in the pod sets both requests and limits for CPU and memory, and requests == limits for both. Guaranteed pods are the absolute last to be evicted under node memory pressure.
  2. Burstable: At least one container sets a request or limit that does not match Guaranteed rules (for instance, requests.memory == limits.memory, requests.cpu: 250m, and limits.cpu omitted or higher).
  3. BestEffort: Zero requests and zero limits set anywhere. BestEffort pods are killed immediately whenever any higher-priority pod needs memory.

When planning node counts, remember that an 8 vCPU / 32 GiB cloud VM does not give pods 8,000m and 32 GiB. Cloud providers reserve CPU and RAM for the kernel, kubelet, containerd, and eviction-hard buffers (100Mi memory + nodefs thresholds), typically leaving around 7.5 vCPU and 28–29 GiB of Allocatable capacity—plus room for DaemonSets (fluent-bit, kube-proxy, CNI agents) running on every node!

Production Deployment Manifest with Runtime Alignment

Notice how the manifest below pins memory requests == limits to prevent memory overcommitment, sizes CPU requests from steady-state telemetry while leaving CPU limits generous (or omitted when cluster LimitRanges allow), and aligns Node.js V8 --max-old-space-size cleanly below the cgroup memory ceiling so garbage collection triggers before the kernel OOM killer fires.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: checkout-api
  namespace: production
spec:
  replicas: 4
  selector:
    matchLabels:
      app: checkout-api
  template:
    metadata:
      labels:
        app: checkout-api
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: api
          image: ghcr.io/example/checkout-api:2.14.0
          env:
            # Leave ~25% memory headroom for native buffers, stacks, and page cache
            - name: NODE_OPTIONS
              value: "--max-old-space-size=768"
          resources:
            requests:
              cpu: "250m"
              memory: "1Gi"
            limits:
              # Allow bursting across spare node cores during JIT/TLS spikes;
              # set cpu limit only if strict tenant noisy-neighbor capping is required
              cpu: "1000m"
              memory: "1Gi"
          readinessProbe:
            httpGet:
              path: /healthz/ready
              port: 8080
            periodSeconds: 5
          livenessProbe:
            httpGet:
              path: /healthz/live
              port: 8080
            periodSeconds: 15

If you deploy Go services instead of Node.js, set GOMEMLIMIT=850MiB inside env alongside GOGC=100 (or rely on automemlimit reading cgroup v2 memory.max). Without runtime heap awareness, both JVM (-XX:MaxRAMPercentage=75.0) and Go runtimes either underuse available pod memory or grow buffers slightly past 1Gi right as a sudden burst triggers an ungraceful OOMKilled.

Prometheus Queries for Telemetry-Driven Rightsizing

Never guess resource profiles blindly—query Prometheus across a full 7-day business cycle (including weekly batch jobs and Monday morning spikes) to derive factual requests and limits:

# 1. Recommended CPU request: 95th percentile CPU burn per pod over 7 days
quantile(0.95,
  rate(container_cpu_usage_seconds_total{namespace="production",container="api"}[5m])
)

# 2. Check whether CFS CPU throttling is silently hurting latency (> 5% throttled periods)
sum by (pod) (rate(container_cpu_cfs_throttled_periods_total{namespace="production",container="api"}[5m]))
/
sum by (pod) (rate(container_cpu_cfs_periods_total{namespace="production",container="api"}[5m]))

# 3. Recommended memory ceiling: max working_set_bytes * 1.25 safety headroom
max(container_memory_working_set_bytes{namespace="production",container="api"}) * 1.25

Look specifically at query #2 (container_cpu_cfs_throttled_periods_total / container_cpu_cfs_periods_total). Even when average CPU utilization sits at a seemingly calm 18%, multi-threaded runtimes frequently suffer 30–60% throttled 100ms periods because bursts collide with low CPU limits. Raising or removing artificial CPU limits while keeping accurate CPU requests often cuts p99 latency in half at zero extra infrastructure cost.

Common Sizing Mistakes and Cluster Traps

Guard against four high-impact mistakes during cluster capacity reviews:

  • Using HPA CPU percentage targets against inflated requests: HorizontalPodAutoscaler calculates utilization relative to requests.cpu. If you over-provision requests.cpu: "2000m" when the pod idles at 100m, average utilization hovers at 5%, meaning an 80% HPA rule never triggers until traffic grows 16x—long after database pools or memory saturate.
  • Forgetting DaemonSet overhead per node: Monitoring, log shippers, and CNI plugins routinely consume 300m–600m CPU and 512Mi–1Gi RAM on every single node. Ignoring them causes pods sized neatly for 4 vCPU nodes to sit forever in Pending (Insufficient cpu).
  • Sharing /dev/shm default 64Mi cap with headless Chrome or PyTorch: Kubernetes mounts /dev/shm at 64Mi regardless of pod memory limits, crashing browser automation or ML data loaders unless you mount an explicit emptyDir: { medium: Memory, sizeLimit: 512Mi } volume at /dev/shm (which counts toward pod limits.memory!).
  • Applying strict limits.cpu to initContainers: Migrations and bundle decompression inside initContainers run once and exit; giving them tiny CPU limits stretches pod rollouts from 3 seconds to 90 seconds unnecessarily.

Verifying Capacity Fit and Runtime Stability

Before applying updated resource manifests across production namespaces, verify cluster fit and runtime metrics systematically:

  1. Plug replica counts, per-pod requests, limits, and target worker node specs into the Interactive Kubernetes Resource Calculator to confirm Allocatable headroom remains safely below 80% per node. Also verify namespace ResourceQuota and LimitRange policies match your chosen ratios, because clusters enforcing strict default LimitRange multipliers reject or mutate manifests silently during admission if limits exceed namespace quotas.
  2. Run kubectl describe pod <name> on canary pods to verify QoS Class matches your reliability tier (Guaranteed or intentional Burstable) and OOMKilled count stays zero over a 48-hour burn-in.
  3. Monitor container_cpu_cfs_throttled_periods_total alongside p99 HTTP latency before and after tuning to confirm zero CFS stalls remain on user-facing paths. Combine this review with quarterly Vertical Pod Autoscaler (VPA in Off recommendation mode) audits so organic payload growth never catches fixed limits off guard.

FAQ

Why can setting a low Kubernetes CPU limit hurt tail latency even when node CPU is mostly idle?
Linux CFS bandwidth control enforces CPU limits per 100ms quota period. A multi-threaded runtime or Node.js startup spike consuming 200ms of CPU across 4 threads inside 50ms gets frozen until the next 100ms window begins, causing massive p99 latency spikes even on an underutilized node.
Why should memory requests generally equal memory limits in production?
Memory is incompressible—unlike CPU, the kernel cannot slow memory down without triggering the OOM killer. Overcommitting memory requests below limits causes nodes to run out of RAM during concurrent traffic spikes and kills random Burstable pods.
What is the difference between working_set_bytes and RSS when sizing memory?
Kubernetes kubelet OOM eviction decisions evaluate container_memory_working_set_bytes (active memory plus non-reclaimable kernel page cache), not bare RSS. Sizing limits from working_set_bytes p99 plus headroom prevents surprise OOMKills.

Related Examples

Interactive Tools for This Topic