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.
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 |
RememberEviction 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.
kubectl create namespace resources-lab kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yamlkubectl top nodesHow 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.
# payment-api.yaml (illustrative, not applied in this lab)apiVersion: apps/v1kind: Deploymentmetadata: name: payment-api namespace: productionspec: 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-offHow 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.
# memory-hog.yamlapiVersion: v1kind: Podmetadata: name: memory-hog namespace: resources-labspec: 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: 128Mikubectl apply -f memory-hog.yamlsleep 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 137Exit 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.
# cpu-hog.yamlapiVersion: v1kind: Podmetadata: name: cpu-hog namespace: resources-labspec: containers: - name: stress image: polinux/stress command: ["stress"] args: ["--cpu", "2", "--timeout", "600"] resources: requests: cpu: 100m limits: cpu: 200mkubectl apply -f cpu-hog.yamlsleep 60 # CPU stays pinned near the 200m limit even though two threads want morekubectl 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:
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.
# qos-demo.yamlapiVersion: v1kind: Listitems: - 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.9kubectl 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 BestEffortHow 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.
# too-big.yamlapiVersion: v1kind: Podmetadata: name: too-big namespace: resources-labspec: containers: - name: pause image: registry.k8s.io/pause:3.9 resources: requests: cpu: "64" memory: 512Gikubectl apply -f too-big.yamlkubectl 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 nodekubectl 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.
kubectl top pods -n production --containersFor a proper picture, query Prometheus for peaks over a week:
# Peak memory per pod over 7 daysmax_over_time(container_memory_working_set_bytes{namespace="production", container="payment-api"}[7d]) # 95th percentile CPU in cores over 7 daysquantile_over_time(0.95, rate(container_cpu_usage_seconds_total{namespace="production", container="payment-api"}[5m])[7d:5m])Then apply these rules:
- CPU request: set it to the 95th percentile of observed usage, or the average for steady services.
- Memory request: set it to the observed peak plus about 15% headroom.
- 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.
- 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:
# payment-api-vpa.yamlapiVersion: autoscaling.k8s.io/v1kind: VerticalPodAutoscalermetadata: name: payment-api-vpa namespace: productionspec: targetRef: apiVersion: apps/v1 kind: Deployment name: payment-api updatePolicy: updateMode: "Off" # Recommend only, never restart podskubectl describe vpa payment-api-vpa -n production# Read the Lower Bound, Target, and Upper Bound recommendationsHow 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.
# limitrange.yamlapiVersion: v1kind: LimitRangemetadata: name: lab-defaults namespace: resources-labspec: 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: 2Gikubectl 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}'# BurstableHow 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.
# quota.yamlapiVersion: v1kind: ResourceQuotametadata: name: lab-quota namespace: resources-labspec: hard: requests.cpu: "2" requests.memory: 2Gi limits.memory: 4Gi pods: "20"kubectl apply -f quota.yamlkubectl describe quota lab-quota -n resources-labHow to Clean Up
kubectl delete namespace resources-labProduction Best Practices & Common Pitfalls
Common MistakeSetting 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.
TipTrack 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.0to 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
MversusMitrap. Always write binary units such asMiandGifor 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 |