Skip to main content

Configuring Kubernetes Requests, Limits, and QoS

Set Kubernetes CPU and memory requests and limits correctly, see OOMKills and CPU throttling happen, and use QoS, LimitRange, and quotas.

52 Terms

Overview and What You Will Learn

A resource request is the amount of CPU and memory the scheduler reserves for a container, and a limit is the ceiling the node enforces while the container runs. In this lab, you will trigger an OOMKill on purpose, watch CPU throttling happen, see Kubernetes assign QoS classes, force a pod to stay Pending with an impossible request, and set namespace defaults with a LimitRange and ResourceQuota.

Why This Matters in Production

Resource settings decide both where pods are placed and which pods die under pressure. On a shared cluster at a company like Zerodha, dozens of services run on the same nodes at market open. Without memory limits, one leaking service can use up a node's memory and get its neighbours evicted. Without requests, the scheduler has no information to spread pods and packs too many onto one node.

Core Principles

Requests and limits are used by different components at different times. The scheduler reads requests to choose a node, and the kubelet turns limits into Linux cgroup settings that the kernel enforces while the container runs.

flowchart TD P[Pod spec
requests and limits] --> S[Scheduler
places pod using requests] S --> K[Kubelet on the node] K --> C[Kernel cgroups
enforce limits at runtime] C --> M[Memory over limit
container killed] C --> U[CPU over limit
container throttled] classDef spec fill:#475569,color:#FFFFFF classDef sched fill:#326CE5,color:#FFFFFF classDef kill fill:#EF4444,color:#FFFFFF classDef slow fill:#F97316,color:#FFFFFF class P spec class S,K,C sched class M kill class U slow

Memory and CPU behave differently when a container reaches its limit, which is the most important rule in this topic:

Resource Over the limit Symptom
Memory Container is killed OOMKilled, exit code 137, restarts
CPU Container is throttled Slow responses, no restart, hard to spot

CPU is measured in cores, where 1000m equals one vCPU, 500m is half a core, and 100m is a tenth. Memory uses binary units, so write 512Mi. Writing 512M means 512 megabytes in decimal, which is about 5% less.

Kubernetes assigns every pod a Quality of Service (QoS) class from its requests and limits. The class affects which pods the kernel and kubelet sacrifice first when a node runs out of memory.

QoS class Rule Under memory pressure
Guaranteed Every container has CPU and memory requests equal to limits Protected, evicted last
Burstable At least one request or limit is set, but not Guaranteed Evicted when using more than requested
BestEffort No requests or limits at all First to be killed
Remember

Eviction ranks pods that use more memory than they requested first, then by pod priority. QoS class sets the kernel's OOM score, but staying within your request is what keeps a pod safe.

Detailed Step-by-Step Practical Lab

This lab runs on any cluster, including kind, minikube, or a sandbox EKS cluster. The pods use public images and small resource sizes.

How to Prepare a Lab Namespace and Metrics Server

kubectl top needs the metrics server. Many managed clusters include it, and minikube has an addon. For kind, add --kubelet-insecure-tls to the metrics-server arguments.

Bash
kubectl create namespace resources-lab
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
kubectl top nodes
How to Set Requests and Limits on a Deployment

This is the shape of a production manifest. A Deployment needs a selector that matches its pod labels, and the numbers below come from the sizing method later in this lab.

YAML
# payment-api.yaml (illustrative, not applied in this lab)
apiVersion: apps/v1
kind: Deployment
metadata:
name: payment-api
namespace: production
spec:
replicas: 3
selector:
matchLabels:
app: payment-api
template:
metadata:
labels:
app: payment-api
spec:
containers:
- name: payment-api
image: registry.mumbai.devops.in/payment-api:3.1.0
resources:
requests:
cpu: 250m # The scheduler reserves a quarter of a core
memory: 384Mi # Reserved memory, close to the limit on purpose
limits:
memory: 384Mi # Over this, the container is OOMKilled
# No CPU limit: see the throttling section for the trade-off
How to Trigger an OOMKill on Purpose

This pod tries to allocate 250 MB while its limit is 128Mi. The kernel kills it, and restartPolicy: Never keeps the evidence in the pod status.

YAML
# memory-hog.yaml
apiVersion: v1
kind: Pod
metadata:
name: memory-hog
namespace: resources-lab
spec:
restartPolicy: Never
containers:
- name: stress
image: polinux/stress
command: ["stress"]
args: ["--vm", "1", "--vm-bytes", "250M", "--vm-hang", "1"]
resources:
requests:
memory: 100Mi
limits:
memory: 128Mi
Bash
kubectl apply -f memory-hog.yaml
sleep 20
kubectl get pod memory-hog -n resources-lab
# STATUS shows OOMKilled
kubectl get pod memory-hog -n resources-lab \
-o jsonpath='{.status.containerStatuses[0].state.terminated.reason} {.status.containerStatuses[0].state.terminated.exitCode}'
# Expected: OOMKilled 137

Exit code 137 means 128 plus signal 9, so the process was killed with SIGKILL. In a Deployment, the pod would restart and then show CrashLoopBackOff.

How to Observe CPU Throttling

This pod runs two busy threads but is limited to 200m of CPU. It is never killed, it is only slowed down.

YAML
# cpu-hog.yaml
apiVersion: v1
kind: Pod
metadata:
name: cpu-hog
namespace: resources-lab
spec:
containers:
- name: stress
image: polinux/stress
command: ["stress"]
args: ["--cpu", "2", "--timeout", "600"]
resources:
requests:
cpu: 100m
limits:
cpu: 200m
Bash
kubectl apply -f cpu-hog.yaml
sleep 60
# CPU stays pinned near the 200m limit even though two threads want more
kubectl top pod cpu-hog -n resources-lab
# Read the throttling counters (cgroup v2 path first, cgroup v1 as fallback)
kubectl exec -n resources-lab cpu-hog -- sh -c \
'cat /sys/fs/cgroup/cpu.stat 2>/dev/null || cat /sys/fs/cgroup/cpu/cpu.stat'

Compare nr_throttled with nr_periods. In this lab the ratio is close to 100%, because the process wants far more CPU than its limit. For a real service, a throttled share above about 10% usually means the limit is hurting latency.

In production, measure throttling with Prometheus instead of exec:

TEXT
sum by (pod) (rate(container_cpu_cfs_throttled_periods_total{namespace="production"}[5m]))
/
sum by (pod) (rate(container_cpu_cfs_periods_total{namespace="production"}[5m]))
How to See QoS Classes Assigned

Create three pods that differ only in their resource settings, then read the class Kubernetes chose.

YAML
# qos-demo.yaml
apiVersion: v1
kind: List
items:
- apiVersion: v1
kind: Pod
metadata:
name: qos-guaranteed
namespace: resources-lab
spec:
containers:
- name: pause
image: registry.k8s.io/pause:3.9
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
cpu: 100m
memory: 64Mi
- apiVersion: v1
kind: Pod
metadata:
name: qos-burstable
namespace: resources-lab
spec:
containers:
- name: pause
image: registry.k8s.io/pause:3.9
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
cpu: 200m
memory: 128Mi
- apiVersion: v1
kind: Pod
metadata:
name: qos-besteffort
namespace: resources-lab
spec:
containers:
- name: pause
image: registry.k8s.io/pause:3.9
Bash
kubectl apply -f qos-demo.yaml
kubectl get pods -n resources-lab \
-o custom-columns=NAME:.metadata.name,QOS:.status.qosClass
# qos-guaranteed Guaranteed
# qos-burstable Burstable
# qos-besteffort BestEffort
How to Prove the Scheduler Uses Requests

Ask for more CPU than any node has. The pod never starts, even though the container would use almost nothing, because the scheduler reasons from the request.

YAML
# too-big.yaml
apiVersion: v1
kind: Pod
metadata:
name: too-big
namespace: resources-lab
spec:
containers:
- name: pause
image: registry.k8s.io/pause:3.9
resources:
requests:
cpu: "64"
memory: 512Gi
Bash
kubectl apply -f too-big.yaml
kubectl describe pod too-big -n resources-lab | grep -A3 Events
# Warning FailedScheduling 0/3 nodes are available: 3 Insufficient cpu, 3 Insufficient memory
# See reserved capacity versus real capacity on a node
kubectl describe node | grep -A8 "Allocated resources"
How to Find the Right Values by Measuring

Never guess. Run the service under realistic traffic for at least a few days, then size from the data.

Bash
kubectl top pods -n production --containers

For a proper picture, query Prometheus for peaks over a week:

Bash
# Peak memory per pod over 7 days
max_over_time(container_memory_working_set_bytes{namespace="production", container="payment-api"}[7d])
# 95th percentile CPU in cores over 7 days
quantile_over_time(0.95, rate(container_cpu_usage_seconds_total{namespace="production", container="payment-api"}[5m])[7d:5m])

Then apply these rules:

  1. CPU request: set it to the 95th percentile of observed usage, or the average for steady services.
  2. Memory request: set it to the observed peak plus about 15% headroom.
  3. Memory limit: set it equal to the memory request, so the pod cannot take more than the scheduler reserved. If you cannot predict peaks, allow up to 25% above the request.
  4. CPU limit: leave it unset for latency-sensitive services, or set it generously at 2 to 4 times the request, and watch the throttling ratio.

If the Vertical Pod Autoscaler is installed, it can calculate these for you in recommendation-only mode, which changes nothing:

YAML
# payment-api-vpa.yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: payment-api-vpa
namespace: production
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: payment-api
updatePolicy:
updateMode: "Off" # Recommend only, never restart pods
Bash
kubectl describe vpa payment-api-vpa -n production
# Read the Lower Bound, Target, and Upper Bound recommendations
How to Set Namespace Defaults with a LimitRange

A LimitRange injects defaults into pods that declare nothing, and rejects pods outside the min and max. It only affects pods created after it exists, and it turns BestEffort pods into Burstable ones.

YAML
# limitrange.yaml
apiVersion: v1
kind: LimitRange
metadata:
name: lab-defaults
namespace: resources-lab
spec:
limits:
- type: Container
defaultRequest: # Injected as requests when a container sets none
cpu: 100m
memory: 128Mi
default: # Injected as limits when a container sets none
cpu: 500m
memory: 256Mi
min:
cpu: 50m
memory: 64Mi
max:
cpu: "2"
memory: 2Gi
Bash
kubectl apply -f limitrange.yaml
kubectl run no-resources --image=registry.k8s.io/pause:3.9 -n resources-lab
kubectl get pod no-resources -n resources-lab \
-o jsonpath='{.spec.containers[0].resources}'
# Shows the injected defaults
kubectl get pod no-resources -n resources-lab -o jsonpath='{.status.qosClass}'
# Burstable
How to Cap a Whole Namespace with a ResourceQuota

A LimitRange shapes each container, while a ResourceQuota caps the namespace total. Once a quota covers CPU or memory, every new pod must declare those values, or get them from a LimitRange.

YAML
# quota.yaml
apiVersion: v1
kind: ResourceQuota
metadata:
name: lab-quota
namespace: resources-lab
spec:
hard:
requests.cpu: "2"
requests.memory: 2Gi
limits.memory: 4Gi
pods: "20"
Bash
kubectl apply -f quota.yaml
kubectl describe quota lab-quota -n resources-lab
How to Clean Up
Bash
kubectl delete namespace resources-lab

Production Best Practices & Common Pitfalls

Common Mistake

Setting requests equal to limits everywhere to get Guaranteed QoS without measuring. If you reserve 2 CPUs for a pod that normally uses 200m, 1.8 CPUs of that node are blocked, and the cluster looks full while it is mostly idle, so new pods stay Pending.

Tip

Track the gap between requested and used resources. A big gap means you are paying for idle capacity, and a pod regularly above its request is the first candidate for eviction.

  • Weigh the CPU limit trade-off. A CPU limit can throttle a container for part of every 100 ms period even when the node is idle, which adds latency. Many teams set CPU requests and omit CPU limits for latency-sensitive services, and keep CPU limits where noisy neighbours are a real risk.
  • Keep memory headroom for spikes. A container running at 90% of its memory limit will be OOMKilled on any traffic spike or garbage collection pause.
  • Tune the JVM to the limit. Modern JVMs read the container limit but default to using only 25% of it for the heap. Set -XX:MaxRAMPercentage=75.0 to use more, and leave the rest for metaspace, threads, and native memory, or the container gets OOMKilled.
  • Tune Node.js to the limit. Set NODE_OPTIONS=--max-old-space-size= to about 75% of the memory limit in MiB, because the V8 heap is only part of the process's memory.
  • Set requests on every workload. Pods without them are BestEffort, so they are placed blindly and evicted first, and tools like Cluster Autoscaler cannot reason about them.
  • Do not confuse OOMKilled with Evicted. OOMKilled means the container hit its own limit, while Evicted means the kubelet removed the pod because the whole node ran short of memory.
  • Mind the M versus Mi trap. Always write binary units such as Mi and Gi for memory.

Quick Reference & Troubleshooting Commands

Command Description
kubectl top pods -n NS --containers See live CPU and memory per container
kubectl top pods --sort-by=memory -n NS Find the biggest memory users
kubectl get pod NAME -o jsonpath='{.status.qosClass}' Check a pod's QoS class
kubectl describe node NODE Compare allocated requests with node capacity
kubectl describe pod NAME Read OOMKilled reasons and FailedScheduling events
kubectl describe limitrange -n NS View the namespace default resource policy
kubectl describe quota -n NS View namespace quota usage

Resources

Velero vs etcd Snapshot: Which Do You Need?

Velero vs etcd Snapshot: Which Do You Need?

Velero and etcd snapshots protect different layers of a Kubernetes cluster. See what each backs up, what each misses, and why most DR needs both.

11 min read•Aug 2026
Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient cuts the sidecar tax at L4, but L7 adds waypoint hops, and Linkerd stable builds now come from Buoyant. Choose with tests.

11 min read•Aug 2026
Nginx Ingress vs Traefik vs Gateway API in 2026

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-NGINX is retired. Compare Traefik and Gateway API controllers as replacements, plus a safe migration plan that avoids outages.

10 min read•Aug 2026
OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno compared for 2026: Rego vs YAML, mutation, reporting, and operations, plus how to pick a Kubernetes policy engine.

10 min read•Aug 2026
Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize compared for 2026 - templating vs patching, Helm 4's new features, and why most production teams end up running both.

5 min read•Aug 2026
Prometheus vs Datadog vs New Relic: Real Costs

Prometheus vs Datadog vs New Relic: Real Costs

Prometheus, Datadog, and New Relic compared for 2026 - real pricing at scale, hidden cost drivers, and which fits a Kubernetes-heavy stack.

5 min read•Aug 2026
Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter on EKS: scale-up speed, bin-packing, Spot handling, Auto Mode limits and a safe migration path, with v1 NodePool YAML.

11 min read•Aug 2026
GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE, EKS, and AKS compared for 2026 - control plane pricing, Autopilot vs Karpenter vs Node Auto Provisioning, and which platform actually fits your team.

5 min read•Aug 2026
K3s vs K8s vs MicroK8s: Which Distro in 2026?

K3s vs K8s vs MicroK8s: Which Distro in 2026?

Compare K3s, upstream Kubernetes and MicroK8s on footprint, datastores, HA and updates, and pick the right fit for edge, dev or production.

10 min read•Aug 2026
Canary Deployments with Argo Rollouts & Flagger

Canary Deployments with Argo Rollouts & Flagger

Ship to 5% of users first and auto-rollback on bad metrics: canary deployments on Kubernetes with Argo Rollouts, Flagger, and Gateway API.

11 min read•Jun 2026
OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry in practice: instrument a Node.js service, run a production Collector, sample traces and link metrics, logs and traces in Grafana.

11 min read•Jun 2026
Kubernetes Cost Optimization Without SLO Risk

Kubernetes Cost Optimization Without SLO Risk

Kubernetes clusters average about 8% CPU use. Cut waste safely with request rightsizing, autoscaling, spot, and OpenCost, keeping SLOs.

11 min read•Jun 2026
ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD compared for 2026: UI, multi-tenancy, Helm, image automation and pruning risks, with a clear guide to picking your GitOps engine.

10 min read•Jun 2026

Explore More in Kubernetes Networking and Traffic Management

All 6 Topics

Frequently Asked Questions

Is Configuring Kubernetes Requests, Limits, and QoS free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Configuring Kubernetes Requests, Limits, and QoS topic cover?

Set Kubernetes CPU and memory requests and limits correctly, see OOMKills and CPU throttling happen, and use QoS, LimitRange, and quotas.

Found a mistake, an outdated step or a broken link?