# Resource management: requests, limits, namespaces, quotas

Tell the scheduler what each container needs, stop one app from starving others, divide a cluster between teams with namespaces and quotas, and recognise an OOM kill.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 7. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/07-resource-management

## What you will learn

- Explain CPU and memory requests and limits, and what the scheduler does with each
- Recognise an OOMKilled container and its exit code 137
- Use namespaces to scope a team's objects
- Cap a namespace with a ResourceQuota and set defaults with a LimitRange
- Read real usage with kubectl top

> **Lab status.** **Verified lab:** the quota stopping a Deployment at 5 of 7 Pods, LimitRange defaults, a real OOM kill and kubectl top, on the course's EKS cluster. The output shown is real. <br />**Code walkthrough:** none. <br />**Cloud lab:** none needed; works on kind (kubectl top needs metrics-server).

A cluster is shared: many apps, often many teams, on the same nodes. Without rules, one app with a memory
leak can starve everything next to it. This lesson covers the rules: what each container asks for, what it
may use, and what each team gets in total.

## Requests and limits

Every container can declare two numbers per resource:

```yaml
resources:
  requests:
    cpu: 100m # 0.1 of a CPU core, reserved for scheduling
    memory: 64Mi
  limits:
    memory: 128Mi # the most it may ever use
```

- **Requests** are a reservation. The scheduler only places a Pod on a node whose free allocatable capacity
  covers the requests. A node can look idle and still refuse a Pod, because its capacity is already reserved.
- **Limits** are a ceiling, enforced by the kernel. Going over a **CPU** limit means being throttled (slowed
  down). Going over a **memory** limit means being **killed**, because memory can't be taken back.

> **Figure.** Two gauges. Memory, 0 to 320Mi: 0 to 64Mi is the request, reserved; 64 to 128Mi is allowed if the node has room; above the 128Mi limit the kernel kills the container. shop-web's real usage is about 11Mi from kubectl top. The memory-hog Pod tried bytearray of 300 MiB and was OOMKilled with exit code 137, which is 128 plus 9 for SIGKILL. CPU, 0 to 1000m: the request is 100m; with no CPU limit the container may use idle CPU on the node; if limits.cpu were 500m, going above it would mean throttling, never a kill.
>
> shop-web's real request, limit and usage, and the memory-hog Pod from the next section.

A common practice: always set requests, set a memory limit, and leave out the CPU limit unless you need hard
isolation, because CPU throttling causes latency spikes that are hard to see.

### An OOM kill, for real

This Pod tries to allocate 300 MiB with a limit of 128 MiB:

```yaml
# 07-oom.yaml (excerpt)
command: ["python", "-c", "x = bytearray(300 * 1024 * 1024); print('allocated'); import time; time.sleep(60)"]
resources:
  requests:
    memory: 64Mi
  limits:
    memory: 128Mi
```

```text
$ kubectl get pod memory-hog
NAME         READY   STATUS      RESTARTS   AGE
memory-hog   0/1     OOMKilled   0          23s
$ kubectl get pod memory-hog -o jsonpath='{.status.containerStatuses[0].state.terminated}'
{"containerID":"containerd://28853a26301e33bf3f3b7490aa93ab1b6d7a6ba19b7ae2705dde4560f4c12041","exitCode":137,"finishedAt":"2026-11-09T06:03:42Z","reason":"OOMKilled",...}
```

`OOMKilled`, **exit code 137** (128 + 9, the signal number of SIGKILL). It never printed "allocated". When a
Pod restarts over and over with exit code 137, look at its memory limit and its real usage before anything
else.

### Real usage with kubectl top

metrics-server reports what Pods actually use:

```text
$ kubectl top nodes
NAME                                          CPU(cores)   CPU(%)   MEMORY(bytes)   MEMORY(%)
ip-10-42-0-115.ap-south-1.compute.internal    88m          4%       738Mi           22%
ip-10-42-28-149.ap-south-1.compute.internal   91m          4%       738Mi           22%
$ kubectl top pods -A --sort-by=memory
NAMESPACE     NAME                                            CPU(cores)   MEMORY(bytes)
kube-system   aws-node-dtf7s                                  5m           165Mi
kube-system   aws-node-hqdfw                                  4m           165Mi
kube-system   ebs-csi-controller-5b647c79f4-5nmnx             6m           63Mi
...
default       shop-web-55d49ccc4b-vrdz4                       1m           11Mi
```

shop-web uses about 11 MiB against a 64 MiB request. Comparing real usage with requests over a week is how
you size them: too high wastes nodes, too low risks OOM kills and crowded nodes.

> **Figure.** Two bars for one t3.medium node with 1930m allocatable CPU. Top, what the scheduler sees: system Pods plus two Pods requesting 600m each leave less than 600m free, so a new Pod requesting 600m does not fit. The real event from lesson 10 reads: Warning FailedScheduling default-scheduler 0/2 nodes are available: 2 Insufficient cpu. Bottom, what the node uses: 88m, 4 percent, nearly idle.
>
> Why a nearly idle node can still refuse a Pod: the scheduler adds up requests, never live usage. The Pod mix is an example.

## Namespaces

A **namespace** scopes names and policies inside one cluster: two teams can each have a `web` Deployment,
RBAC permissions and quotas attach to a namespace, and `kubectl delete namespace team-a` removes everything in
it. As lesson 1 warned, it is **not** a network or security boundary by itself: Pods in different namespaces
can still reach each other unless a NetworkPolicy says otherwise.

## Quotas and defaults

```yaml
# 07-team-a.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: team-a
---
apiVersion: v1
kind: ResourceQuota
metadata:
  name: team-a-quota
  namespace: team-a
spec:
  hard:
    requests.cpu: "1"
    requests.memory: 1Gi
    limits.memory: 2Gi
    pods: "5"
---
apiVersion: v1
kind: LimitRange
metadata:
  name: team-a-defaults
  namespace: team-a
spec:
  limits:
    - type: Container
      default:
        memory: 128Mi # limit, if the container sets none
      defaultRequest:
        cpu: 100m # request, if the container sets none
        memory: 64Mi
```

- A **ResourceQuota** caps the namespace's total: here at most 5 Pods and 1 CPU of requests.
- A **LimitRange** fills in defaults for containers that don't set their own. Once a quota covers CPU and
  memory, every Pod must declare them, and the LimitRange makes sure they do.

Then ask for 7 replicas:

```text
$ kubectl create deployment api -n team-a --image=626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v1 --replicas=7
deployment.apps/api created
$ kubectl get deployment api -n team-a
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
api    5/7     5            5           21s
$ kubectl describe replicaset -n team-a api-8998d56f9 | tail -2
  Warning  FailedCreate      37s                replicaset-controller  Error creating: pods "api-8998d56f9-nbdgs" is forbidden: exceeded quota: team-a-quota, requested: pods=1, ...
  Warning  FailedCreate      37s (x9 over 37s)  replicaset-controller  (combined from similar events): Error creating: pods "api-8998d56f9-vdqpj" is forbidden: exceeded quota: ...
$ kubectl get pod api-8998d56f9-m9qfq -n team-a -o jsonpath='{.spec.containers[0].resources}'
{"limits":{"memory":"128Mi"},"requests":{"cpu":"100m","memory":"64Mi"}}
$ kubectl describe resourcequota team-a-quota -n team-a
Name:            team-a-quota
Namespace:       team-a
Resource         Used   Hard
--------         ----   ----
limits.memory    640Mi  2Gi
pods             5      5
requests.cpu     500m   1
requests.memory  320Mi  1Gi
```

What happened, step by step:

1. The Deployment was accepted, and its ReplicaSet tried to create 7 Pods.
2. Pods 1 to 5 were admitted. The `kubectl create deployment` command set no resources, so the LimitRange
   filled in 100m CPU, 64Mi request and 128Mi limit, as the JSON shows.
3. Pod 6 would have made `pods` 6 of 5, so the API server refused it. The ReplicaSet keeps trying and logs
   `FailedCreate` events.

> **Figure.** One cluster split into namespaces: default with the shop-web Deployment and Service; kube-system with aws-node, kube-proxy, coredns and metrics-server; and team-a. In team-a, kubectl create deployment api with 7 replicas: api 1 to 5 are admitted, api 6 and 7 fail with FailedCreate, exceeded quota, recorded on the ReplicaSet. ResourceQuota team-a-quota usage: pods 5 of 5, full; requests.cpu 500m of 1; requests.memory 320Mi of 1Gi; limits.memory 640Mi of 2Gi. LimitRange team-a-defaults gives containers with no resources requests of 100m CPU and 64Mi memory and a 128Mi limit. Names are per namespace, and a namespace is not a network wall.
>
> The lab's team-a namespace after asking for 7 replicas: one picture of namespaces, the quota and the LimitRange.

The Deployment shows `5/7` and never reaches 7. When a Deployment is stuck below its replica count with no
crashing Pods, describe its ReplicaSet: quota errors only appear there.

## Mission: Give a team a fair share, and break it on purpose

Create the team-a namespace with the quota and limit range from this lesson, create a 7-replica Deployment in it, and record how many Pods run, the quota usage and one FailedCreate event. Then run the memory-hog Pod and record its reason and exit code.

- You need: 07-team-a.yaml and 07-oom.yaml
- You'll have: ~/resources.txt

```sh
$ kubectl apply -f 07-team-a.yaml
$ kubectl create deployment api -n team-a --image=<your-registry>/shop-web:v1 --replicas=7
$ sleep 15; kubectl get deployment api -n team-a > ~/resources.txt
$ kubectl describe resourcequota team-a-quota -n team-a >> ~/resources.txt
$ kubectl apply -f 07-oom.yaml; sleep 20
$ kubectl get pod memory-hog -o jsonpath='{.status.containerStatuses[0].state.terminated.reason} {.status.containerStatuses[0].state.terminated.exitCode}' >> ~/resources.txt
$ kubectl delete namespace team-a && kubectl delete pod memory-hog
```

You should see `5/7`, `pods 5 5`, and `OOMKilled 137`.

## Try it

- Apply the team-a namespace with its quota and limit range, and describe the quota.
- Create a Deployment of 7 replicas in team-a and count how many Pods start.
- Find the FailedCreate events on the ReplicaSet.
- Run the memory-hog Pod and read its terminated state.
- Do the mini mission and keep `~/resources.txt`.

## Quiz

1. What does the scheduler use to decide whether a Pod fits on a node?
   - The Pod's limits
   - **The Pod's requests, compared with the node's allocatable capacity minus other requests** (answer)
   - Current CPU usage
   Why: Requests are reservations. Limits only cap usage at runtime. That's why a node can look idle yet refuse new Pods.

2. A container exceeds its memory limit. What happens?
   - It is slowed down
   - **The kernel kills it (OOMKilled, exit code 137) and the kubelet may restart it** (answer)
   - Nothing
   Why: Memory can't be throttled, so going over the limit means a kill. CPU over the limit is throttled instead.

3. A ResourceQuota allows 5 Pods and a Deployment asks for 7. What do you see?
   - 7 Pods running
   - **5 running; the ReplicaSet records FailedCreate events saying the quota was exceeded** (answer)
   - The Deployment is rejected entirely
   Why: The Deployment is accepted, but the ReplicaSet can't create Pods beyond the quota, exactly as in the lab.

## Resources

- [Resource management for Pods and containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) (Kubernetes)
- [Namespaces](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/) (Kubernetes)
- [Resource quotas](https://kubernetes.io/docs/concepts/policy/resource-quotas/) (Kubernetes)
- [Limit ranges](https://kubernetes.io/docs/concepts/policy/limit-range/) (Kubernetes)
