πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

Kubernetes lets you define CPU and memory (RAM) constraints for containers using resource requests and limits. This ensures fair resource allocation, prevents node overcommitment, and improves cluster stability and performance. Today you’ll learn how to configure, monitor, and troubleshoot them.

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


Requests vs limits: the scheduler places pods by summing requests against node allocatable; the kubelet enforces limits with cgroups, throttling CPU and OOMKilling memory; requests and limits set the QoS class Guaranteed, Burstable or BestEffort

Download a high-resolution copy of this diagram here for future reference.

πŸ’‘

πŸ“š Key Learnings

πŸ”Ή What are resource requests and limits, and how do they work (deep understanding)?
πŸ”Ή Difference between:

  • requests: minimum guaranteed resources for scheduling
  • limits: max allowed usage, enforced at runtime


πŸ”Ή Scheduling decisions based on requests, not limits
πŸ”Ή What happens when a container exceeds its limit (OOMKilled, throttling)
πŸ”Ή How to apply resource constraints at:

  • Container level
  • Namespace level (via ResourceQuota)


πŸ”Ή CPU units (m = millicores), memory units (Mi, Gi)
πŸ”Ή Monitoring resource usage with kubectl top, metrics-server, or Prometheus
πŸ”Ή QoS Classes in Kubernetes

πŸ”Ή Best practices for setting appropriate values

🧠 Learn here

Resource Requests and Limits in Kubernetes:

In Kubernetes, resource requests and limits define how much CPU and memory (RAM) a container can use:

  • Requests: The minimum amount of resources guaranteed to the container. Kubernetes uses this during scheduling.
  • Limits: The maximum amount of resources the container is allowed to use. The container is throttled or killed if it tries to exceed this.

Difference between Requests and Limits

Aspect requests limits
Purpose Minimum guaranteed resources Max allowed usage
Used by Scheduler βœ… Yes ❌ No
Enforced at runtime ❌ No βœ… Yes
Behavior when exceeded Runs normally CPU: throttled, Memory: OOMKilled

How Kubernetes Makes Scheduling Decisions

The Kube-scheduler uses requests to place pods onto nodes. It ensures the node has at least that amount of available CPU/Memory. limits are not considered during scheduling.

YAML Example:

apiVersion: v1
kind: Pod
metadata:
  name: app-pod
spec:
  containers:
  - name: app-container
    image: nginx
    resources:
      requests:
        memory: "256Mi"
        cpu: "250m"
      limits:
        memory: "512Mi"
        cpu: "500m"

What Happens When a Container Exceeds Its Limits?

  • CPU Limit Exceeded: The container is throttled (limited in processing speed).
  • Memory Limit Exceeded: The container is terminated with an OOMKilled error.

Check for OOMKilled:

kubectl get pod app-pod
kubectl describe pod app-pod | grep -A5 State

Resource Constraints at Different Levels

1. Container Level – Defined in the resources section (see YAML above)

2. Namespace Level – Use ResourceQuota to limit usage for the entire namespace

YAML: ResourceQuota.yaml

apiVersion: v1
kind: ResourceQuota
metadata:
  name: mem-cpu-quota
  namespace: dev-team
spec:
  hard:
    requests.cpu: "2"
    requests.memory: "2Gi"
    limits.cpu: "4"
    limits.memory: "4Gi"

Apply it:

kubectl apply -f resource-quota.yaml

CPU and Memory Units

  • CPU:
    • 1 core = 1000m
    • 500m = 0.5 CPU cores
  • Memory:
    • Mi = Mebibytes (1Mi = 1024^2 bytes)
    • Gi = Gibibytes (1Gi = 1024^3 bytes)

Monitoring Resource Usage

1. Metrics Server

Install:

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

Check usage:

kubectl top pods
kubectl top nodes

Prometheus + Grafana

Install via Helm:

helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install k8s-monitor prometheus-community/kube-prometheus-stack -n monitoring --create-namespace

Use Grafana dashboards to track CPU/Memory.


QoS Classes in Kubernetes

Kubernetes assigns QoS Classes to pods based on their resource requests and limits for CPU and memory. These classes influence pod eviction during node resource pressure (especially memory).

There are 3 QoS classes:

QoS Class Condition
Guaranteed Requests = Limits for both CPU and memory for all containers
Burstable At least one container has a CPU or memory request or limit, but the pod doesn't meet the Guaranteed rules
BestEffort No container has any CPU or memory request or limit

Why QoS Classes Matter?

  • During memory pressure, the kubelet first evicts pods using more than they requested, then looks at Priority and usage. In practice that means:
    • BestEffort β†’ evicted first
    • Burstable β†’ evicted next
    • Guaranteed β†’ evicted last
  • Helps prioritize critical workloads.

YAML Examples of Each QoS Class

1. Guaranteed

apiVersion: v1
kind: Pod
metadata:
  name: guaranteed-pod
spec:
  containers:
    - name: app
      image: nginx
      resources:
        requests:
          memory: "128Mi"
          cpu: "250m"
        limits:
          memory: "128Mi"
          cpu: "250m"
βœ… Limits = Requests for both CPU and memory β‡’ Guaranteed QoS

2. Burstable

apiVersion: v1
kind: Pod
metadata:
  name: burstable-pod
spec:
  containers:
    - name: app
      image: nginx
      resources:
        requests:
          memory: "64Mi"
          cpu: "100m"
        limits:
          memory: "128Mi"
          cpu: "500m"
βœ… Requests < Limits for at least one resource β‡’ Burstable QoS

3. BestEffort

apiVersion: v1
kind: Pod
metadata:
  name: besteffort-pod
spec:
  containers:
    - name: app
      image: nginx
❌ No requests/limits set β‡’ BestEffort QoS

πŸ”§ Check QoS Class of a Pod

kubectl get pod <pod-name> -o jsonpath='{.status.qosClass}'

Example:

kubectl get pod guaranteed-pod -o jsonpath='{.status.qosClass}'
# Output: Guaranteed

πŸ’‘ Useful Commands

  • View all pod QoS classes in a namespace:
kubectl get pods -o custom-columns="NAME:.metadata.name,QOS:.status.qosClass"

QOS Best Practices

  • For critical apps, use Guaranteed QoS.
  • For normal workloads, Burstable is fine with sane requests and upper limits.
  • Avoid BestEffort unless absolutely non-critical.
  • Use ResourceQuota at the namespace level to control overall usage.

Request & Limit Best Practices

  • Always define requests, and set a memory limit. CPU limits are optional: they throttle a container even when the node has idle CPU, so many teams skip them for latency-sensitive apps.
  • Set realistic values based on past usage.
  • Use kubectl top and Prometheus metrics to tune values.
  • Avoid overcommitting memory.
  • Apply LimitRange and ResourceQuota in namespaces for governance.
  • Monitor OOMKilled and throttling events to adjust limits.

πŸ’‘Bonus: Set Default Limits with LimitRange

apiVersion: v1
kind: LimitRange
metadata:
  name: default-limits
  namespace: dev-team
spec:
  limits:
  - default:
      cpu: "500m"
      memory: "512Mi"
    defaultRequest:
      cpu: "250m"
      memory: "256Mi"
    type: Container

Apply it:

kubectl apply -f limit-range.yaml

πŸ“– Learning References

πŸ“Œ Kubernetes Resource Management – Official Docs
πŸ“Œ CPU and Memory Units
πŸ“Œ ResourceQuota
πŸ“Œ LimitRange
πŸ“Œ Understanding Pod Scheduling


πŸ”₯ Challenges

πŸ’‘ Challenge 1: Deploy a container with 128Mi memory request and 256Mi limit
πŸ’‘ Challenge 2: Trigger an OOMKilled state using stress image and inspect logs
πŸ’‘ Challenge 3: Use kubectl top and kubectl describe to analyze resource usage
πŸ’‘ Challenge 4: Apply a LimitRange and deploy a pod without explicit limits to see defaults applied
πŸ’‘ Challenge 5: Set limits too low and observe throttling or restart behavior

πŸ’‘ Challenge 6: Deploy 5 pods with total usage exceeding node capacity β€” observe scheduling behavior
πŸ’‘ Challenge 7: Create a ResourceQuota limiting total CPU and memory in a namespace
πŸ’‘ Challenge 8: Simulate an app that bursts CPU but has a tight limit – identify throttling
πŸ’‘ Challenge 9: Monitor metrics using metrics-server or Prometheus to validate actual usage
πŸ’‘ Challenge 10: Test HPA behavior with different request values and watch scaling impact


πŸ’‘Challenge 11: Final Project: Resource-Constrained Application Environment

πŸ“Œ Create a namespace test-env
πŸ“Œ Add:

  • LimitRange for default per-container limits
  • ResourceQuota to cap total usage

πŸ“Œ Deploy:

  • 2-3 apps with well-defined resource settings
  • 1 pod that intentionally exceeds the quota (watch it fail)

πŸ“Œ Analyze and document the behavior of OOMKilled, throttled, and pending pods

πŸ“Œ Push YAMLs + a summary of findings to GitHub


Solutions

βœ… Challenge 1: Deploy a container with 128Mi memory request and 256Mi limit

apiVersion: v1
kind: Pod
metadata:
  name: mem-limited-pod
spec:
  containers:
  - name: memory-demo
    image: busybox
    command: ["sleep", "3600"]
    resources:
      requests:
        memory: "128Mi"
      limits:
        memory: "256Mi"

βœ… Challenge 2: Trigger an OOMKilled state using stress image and inspect logs

apiVersion: v1
kind: Pod
metadata:
  name: oom-stress-pod
spec:
  containers:
  - name: stress
    image: polinux/stress
    args: ["--vm", "1", "--vm-bytes", "300M", "--vm-hang", "1"]
    resources:
      limits:
        memory: "200Mi"

Inspect with:

kubectl describe pod oom-stress-pod
kubectl logs oom-stress-pod

βœ… Challenge 3: Use kubectl top and kubectl describe to analyze resource usage

kubectl top pod mem-limited-pod
kubectl describe pod mem-limited-pod

βœ… Challenge 4: Apply a LimitRange and deploy a pod without explicit limits

apiVersion: v1
kind: LimitRange
metadata:
  name: default-limit-range
spec:
  limits:
  - default:
      cpu: "500m"
      memory: "256Mi"
    defaultRequest:
      cpu: "250m"
      memory: "128Mi"
    type: Container
apiVersion: v1
kind: Pod
metadata:
  name: no-resource-pod
spec:
  containers:
  - name: app
    image: nginx

βœ… Challenge 5: Set limits too low and observe throttling or restart behavior

apiVersion: v1
kind: Pod
metadata:
  name: low-cpu-pod
spec:
  containers:
  - name: cpu-hog
    image: vish/stress
    args: ["--cpu", "1"]
    resources:
      limits:
        cpu: "100m"

Inspect with:

kubectl describe pod low-cpu-pod
kubectl top pod low-cpu-pod

βœ… Challenge 6: Deploy 5 pods with total usage exceeding node capacity

for i in {1..5}; do
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: stress-$i
spec:
  containers:
  - name: stress
    image: polinux/stress
    args: ["--vm", "1", "--vm-bytes", "300M", "--vm-hang", "1"]
    resources:
      requests:
        memory: "300Mi"
      limits:
        memory: "500Mi"
EOF
done

Check scheduling:

kubectl get pods -o wide

βœ… Challenge 7: Create a ResourceQuota limiting total CPU and memory

apiVersion: v1
kind: ResourceQuota
metadata:
  name: quota-demo
spec:
  hard:
    requests.cpu: "1"
    requests.memory: "1Gi"
    limits.cpu: "2"
    limits.memory: "2Gi"

βœ… Challenge 8: Simulate app that bursts CPU but has a tight limit

apiVersion: v1
kind: Pod
metadata:
  name: bursty-cpu-pod
spec:
  containers:
  - name: stress
    image: vish/stress
    args: ["--cpu", "2"]
    resources:
      limits:
        cpu: "200m"

Check for throttling:

kubectl top pod bursty-cpu-pod   # usage stays pinned at about 200m
# kubectl describe does not show throttling; with Prometheus:
# rate(container_cpu_cfs_throttled_periods_total{pod="bursty-cpu-pod"}[5m])
#   / rate(container_cpu_cfs_periods_total{pod="bursty-cpu-pod"}[5m])

βœ… Challenge 9: Monitor metrics using metrics-server or Prometheus

Ensure metrics-server is deployed:

kubectl top pod

Or use Prometheus:

kubectl get svc -n monitoring | grep prometheus     # find the Prometheus service name
kubectl port-forward svc/<prometheus-service> 9090:9090 -n monitoring

Query:

container_memory_working_set_bytes{container!=""}           # what the OOM killer compares to the limit
rate(container_cpu_usage_seconds_total{container!=""}[5m])   # CPU cores in use (the metric is a counter)

# share of CPU periods that were throttled
rate(container_cpu_cfs_throttled_periods_total[5m]) / rate(container_cpu_cfs_periods_total[5m])

βœ… Challenge 10: Test HPA behavior with different request values

apiVersion: apps/v1
kind: Deployment
metadata:
  name: hpa-demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: hpa-demo
  template:
    metadata:
      labels:
        app: hpa-demo
    spec:
      containers:
      - name: app
        image: vish/stress
        args: ["--cpu", "1"]
        resources:
          requests:
            cpu: "200m"
          limits:
            cpu: "500m"
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: hpa-demo
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: hpa-demo
  minReplicas: 1
  maxReplicas: 5
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50

Monitor scaling:

kubectl get hpa

Challenge 11: Final Project – Resource-Constrained Application Environment

This challenge is about simulating a constrained Kubernetes environment using LimitRanges and ResourceQuotas to observe and analyze behaviors like OOMKilled, throttling, and failed scheduling.

βœ… Step 1: Create Namespace

kubectl create ns test-env

βœ… Step 2: Apply LimitRange

Apply a default per-container resource LimitRange.

# limitrange.yaml
apiVersion: v1
kind: LimitRange
metadata:
  name: container-limits
  namespace: test-env
spec:
  limits:
  - default:
      cpu: "500m"
      memory: "256Mi"
    defaultRequest:
      cpu: "200m"
      memory: "128Mi"
    type: Container
kubectl apply -f limitrange.yaml

βœ… Step 3: Apply ResourceQuota

Restrict total CPU and memory across the namespace.

# resourcequota.yaml
apiVersion: v1
kind: ResourceQuota
metadata:
  name: compute-quota
  namespace: test-env
spec:
  hard:
    requests.cpu: "1"
    requests.memory: "512Mi"
    limits.cpu: "2"
    limits.memory: "1Gi"
kubectl apply -f resourcequota.yaml

βœ… Step 4: Deploy Resource-Aware Apps

4.1 App A

# app-a.yaml
apiVersion: v1
kind: Pod
metadata:
  name: app-a
  namespace: test-env
spec:
  containers:
  - name: app
    image: nginx
    resources:
      requests:
        cpu: "200m"
        memory: "128Mi"
      limits:
        cpu: "300m"
        memory: "256Mi"

4.2 App B

# app-b.yaml
apiVersion: v1
kind: Pod
metadata:
  name: app-b
  namespace: test-env
spec:
  containers:
  - name: app
    image: nginx
    resources:
      requests:
        cpu: "300m"
        memory: "128Mi"
      limits:
        cpu: "400m"
        memory: "256Mi"

4.3 App C

# app-c.yaml
apiVersion: v1
kind: Pod
metadata:
  name: app-c
  namespace: test-env
spec:
  containers:
  - name: app
    image: nginx
    resources:
      requests:
        cpu: "200m"
        memory: "128Mi"
      limits:
        cpu: "400m"
        memory: "256Mi"
kubectl apply -f app-a.yaml
kubectl apply -f app-b.yaml
kubectl apply -f app-c.yaml

βœ… Step 5: Deploy a Pod That Exceeds Quota

# app-over-quota.yaml
apiVersion: v1
kind: Pod
metadata:
  name: app-over-quota
  namespace: test-env
spec:
  containers:
  - name: app
    image: nginx
    resources:
      requests:
        cpu: "500m"
        memory: "512Mi"
      limits:
        cpu: "600m"
        memory: "768Mi"
kubectl apply -f app-over-quota.yaml

Expect kubectl apply to fail with Error from server (Forbidden): ... exceeded quota. Quota is checked at admission, so the pod is never created; Pending is what you see when no node has room, not when a quota is exceeded.

βœ… Step 6: Analyze Pod Behavior

Check Pod Status:

kubectl get pods -n test-env

Inspect the quota:

kubectl describe resourcequota compute-quota -n test-env   # used vs hard limits
# app-over-quota was never created, so there is no pod to describe:
# the reason is in the kubectl apply error ("exceeded quota")

Check for OOMKilled / Throttled:

kubectl get pod app-a -n test-env -o json | jq '.status.containerStatuses[].lastState.terminated.reason'

Or:

kubectl describe pod <pod-name> -n test-env | grep -i "oomkilled"

Monitor Usage:

kubectl top pod -n test-env

βœ… Summary of Findings

  • LimitRange applied default resource limits and requests to all pods that didn't define their own.
  • ResourceQuota enforced an upper cap on total compute usage.
  • The API server rejected app-over-quota at admission with an "exceeded quota" error, so the pod was never created.
  • If a pod exceeds its memory limit during execution, it is OOMKilled.
  • CPU bursts over limits are throttled (can be observed with kubectl top).

βœ… GitHub Push

  1. Add all YAML files:
git add *.yaml
  1. Commit and push:
git commit -m "Challenge 11: Resource-Constrained App Env"
git push origin main

πŸ“Œ Bonus Tip

Use kubectl explain for LimitRange and ResourceQuota to understand the spec fields better:

kubectl explain limitrange.spec.limits
kubectl explain resourcequota.spec.hard

🀷🏻 How to Participate?

βœ… Complete the tasks and challenges.
βœ… Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
βœ… Share the above in a LinkedIn post tagging me (Sandip Das), and use #60DaysOfDevOps to engage with the community!


⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post