Skip to content
LF Cert Trainer

Lesson 34 · Section 3: Scheduling

Lesson 34: Resource limits: the ceiling on what a container may use

What a limit is and how it differs from a request, how the kernel enforces CPU and memory limits in two very different ways, how LimitRange and ResourceQuota set limits for a whole namespace, and how to read and fix an OOMKilled container in the exam. · 20 min read · 5 min video

1/12Resource limits
0:00 / 4:33

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why limits exist

A node is a shared machine. Every container on it draws from the same CPU cores and the same memory, and by default nothing stops one container from taking as much as it can get. One runaway loop or one memory leak is then enough to slow down or kill every other workload on that node, including the kubelet itself.

The previous lesson covered requests: what a container needs, which the scheduler reserves for it. A limit is the other half of the resources block: the most the container is allowed to use, however much is free.

RequestLimit
MeaningThe amount set aside for the containerThe most the container may use
Used bykube-scheduler, to pick a nodeThe kernel on the node, all the time
If the container wants moreIt may take it, if the node has spareCPU: slowed down. Memory: killed
If you leave it outNothing is reservedThe node is the only ceiling

Writing a limit

Limits are set per container, under resources.limits, next to the requests:

apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  containers:
    - name: web
      image: nginx:1.29-alpine
      resources:
        requests:
          cpu: 250m
          memory: 128Mi
        limits:
          cpu: 500m
          memory: 256Mi

This container has 250m CPU and 128Mi reserved, and may burst up to 500m and 256Mi when the node has room. A Pod's total is the sum over its containers; each container is still held to its own limit.

The units are the same as for requests:

ResourceWritten asMeaning
CPU1, 0.5, 500mCores. 1000m is one core, so 500m and 0.5 are the same half core
Memory256Mi, 1GiPowers of two: 1Mi is 1,048,576 bytes
Memory256M, 1GPowers of ten: 1M is 1,000,000 bytes, slightly less than 1Mi
Ephemeral storage2GiLocal disk used by the container's writable layer, logs and emptyDir volumes

How a limit is enforced

From a line of YAML to a kernel rulewatchCRIwritesread bycpumemoryPod speclimits: 500m, 256Mikubeleton the Pod's nodecontainerdcreates the cgroupcgroupcpu.max, memory.maxLinux kernelenforces bothCPU over limitthrottled, not killedMemory over limitOOMKilled, restarted
From a line of YAML to a kernel rule. A limit is not checked by Kubernetes itself. The kubelet hands it to the container runtime, which writes it into the container's cgroup, and the Linux kernel enforces it: CPU by slowing the container down, memory by killing it.

Parts:

  • Pod spec (limits: 500m, 256Mi)
  • kubelet (on the Pod's node)
  • containerd (creates the cgroup)
  • cgroup (cpu.max, memory.max)
  • Linux kernel (enforces both)
  • CPU over limit (throttled, not killed)
  • Memory over limit (OOMKilled, restarted)

Connections:

  • Pod spec to kubelet: watch
  • kubelet to containerd: CRI
  • containerd to cgroup: writes
  • cgroup to Linux kernel: read by
  • Linux kernel to CPU over limit: cpu
  • Linux kernel to Memory over limit: memory

No Kubernetes component watches your container and compares its usage with the limit. The limit travels down to the kernel once, when the container is created:

  1. The kubelet on the Pod's node reads the Pod spec.
  2. It passes the limits to the container runtime through the CRI.
  3. The runtime creates a cgroup for the container and writes the limits into it: cpu.max and memory.max on cgroup v2.
  4. From then on the Linux kernel enforces those two files, with no further help from Kubernetes.

CPU and memory are enforced in very different ways, and this difference is the heart of the lesson.

CPU limitMemory limit
Kind of resourceCompressible: it can be handed out more slowlyIncompressible: memory in use cannot be taken back
What the kernel doesThrottles: the container must wait for its next time sliceKills a process in the container (the OOM killer)
What you seeThe application is slow; nothing is logged in the PodOOMKilled, exit code 137, restart count goes up
Does the container stop?NoYes, and the kubelet restarts it under the Pod's restartPolicy

CPU. A limit of 500m gives the container 50 ms of CPU time in every 100 ms period. Once it has used its 50 ms, all its threads are paused until the next period starts. The container never crashes because of a CPU limit; it just gets slower, which can show up as failed liveness probes or timeouts rather than as an obvious error.

Memory. When a container tries to take more memory than its limit, the kernel's out-of-memory killer ends a process inside it. If that process is the container's main process, the container stops with reason OOMKilled. The Pod is not moved or deleted: the kubelet restarts the container in place, with a growing delay, so a container that always overruns ends up in CrashLoopBackOff.

Under the hood · See the limit from inside the container

On a node with cgroup v2 (every current distribution), the container can read its own limits:

kubectl exec web -- cat /sys/fs/cgroup/cpu.max        # 50000 100000  -> 50 ms per 100 ms = 500m
kubectl exec web -- cat /sys/fs/cgroup/memory.max     # 268435456     -> 256Mi
kubectl exec web -- cat /sys/fs/cgroup/cpu.stat       # nr_throttled counts the paused periods

A container with no limit shows max in both files. Note that tools such as free and nproc inside the container still report the whole node, which is why some applications size their heap or thread pool too large and run into their limit.

Memory counts more than the heap: files written to an emptyDir with medium: Memory and the page cache charged to the container are included as well.

Limits do not take part in scheduling

The scheduler only adds up requests. Limits are ignored when a node is chosen, so the limits of the Pods on a node may add up to far more than the node has. This is called overcommit, and it is normal:

Allocated resources:
  Resource   Requests      Limits
  cpu        1450m (72%)   3500m (175%)
  memory     1800Mi (47%)  5Gi (134%)

Overcommit works as long as the containers do not all burst at once. When they do, CPU is shared out in proportion to the requests, and for memory the node has to get rid of something. That is where quality of service comes in.

Limits decide the quality of service class

Limits decide who dies firstfirstnextlastBestEffortnothing setBurstablerequest below limitGuaranteedrequest = limitNode out of memorywho goes first?
Limits decide who dies first. Kubernetes derives a quality of service class from the requests and limits you set. When a node runs out of memory, Pods with nothing set go first and Pods whose requests equal their limits go last.

Parts:

  • BestEffort (nothing set)
  • Burstable (request below limit)
  • Guaranteed (request = limit)
  • Node out of memory (who goes first?)

Connections:

  • Node out of memory to BestEffort: first
  • Node out of memory to Burstable: next
  • Node out of memory to Guaranteed: last

Kubernetes sorts every Pod into one of three classes, based only on its requests and limits:

ClassRuleUnder memory pressure
GuaranteedEvery container has CPU and memory limits, and each request equals its limitLast to be killed or evicted
BurstableAt least one request or limit is set, but the Pod is not GuaranteedIn the middle; those furthest above their requests go first
BestEffortNo requests and no limits anywhere in the PodFirst to go

You never write the class yourself. Read it with kubectl get pod web -o jsonpath='{.status.qosClass}'.

What you get when you leave something out

You writeWhat the container gets
Request and limitExactly what you wrote
Request onlyThe request is reserved; no ceiling (or the namespace default limit, if a LimitRange sets one)
Limit onlyThe request is set equal to the limit, so the full ceiling is reserved
NeitherNothing reserved, no ceiling (or the namespace defaults, if a LimitRange sets them)
Limit lower than requestThe API server rejects the Pod: must be less than or equal to cpu limit

The "limit only" row surprises people: a Pod with just limits.cpu: "2" asks the scheduler for two whole cores and may stay Pending on a small node.

Limits for a whole namespace

Writing limits into every Pod relies on everybody remembering to do so. Two namespaced objects let an administrator set the rules once. The Namespaces lesson introduced both; here is how they relate to limits.

Namespace rules at admissionAPI server admissioncreatethenover maxover totalfitsNew Podno resources setLimitRangedefaults, min, maxResourceQuotanamespace total403 ForbiddenPod never existsPod storedlimits filled in
Namespace rules at admission. A LimitRange fills in missing requests and limits and checks each container against its minimum and maximum. A ResourceQuota then checks the namespace total. A Pod that breaks either rule is refused and never exists.

Parts:

  • New Pod (no resources set)
  • LimitRange (defaults, min, max), in API server admission
  • ResourceQuota (namespace total), in API server admission
  • 403 Forbidden (Pod never exists)
  • Pod stored (limits filled in)

Connections:

  • New Pod to LimitRange: create
  • LimitRange to ResourceQuota: then
  • LimitRange to 403 Forbidden: over max
  • ResourceQuota to 403 Forbidden: over total
  • ResourceQuota to Pod stored: fits

LimitRange: defaults and bounds per container

apiVersion: v1
kind: LimitRange
metadata:
  name: container-limits
  namespace: shop
spec:
  limits:
    - type: Container
      default:            # limit for a container that sets none
        cpu: 500m
        memory: 256Mi
      defaultRequest:     # request for a container that sets none
        cpu: 100m
        memory: 128Mi
      max:                # no container may have a limit above this
        cpu: "1"
        memory: 1Gi
      min:                # no container may have a request below this
        cpu: 50m
        memory: 32Mi
FieldWhat it does
defaultThe limit given to a container that has none. The name is easy to misread
defaultRequestThe request given to a container that has none
maxThe highest limit allowed
minThe lowest request allowed
maxLimitRequestRatioHow many times larger than its request a limit may be, which caps bursting

A LimitRange works at admission: the API server changes or rejects the Pod while it is being created. Two consequences follow.

  • Existing Pods are not touched. A new or changed LimitRange only affects Pods created afterwards. To apply it to a Deployment's Pods, restart them: kubectl rollout restart deployment web.
  • A rejected Pod never exists. The error comes straight back to whoever created it:
Error from server (Forbidden): pods "big" is forbidden: maximum cpu usage per Container is 1, but limit is 2

Besides type: Container, a LimitRange can set min and max for type: Pod (the sum over all containers) and for type: PersistentVolumeClaim (the requested storage size).

ResourceQuota: a total for the namespace

A LimitRange looks at one container at a time. A ResourceQuota caps the sum over the whole namespace:

apiVersion: v1
kind: ResourceQuota
metadata:
  name: compute
  namespace: shop
spec:
  hard:
    requests.cpu: "2"
    requests.memory: 4Gi
    limits.cpu: "4"
    limits.memory: 8Gi
    pods: "10"

Once a quota tracks limits.cpu or limits.memory, every new Pod in the namespace must set that limit, or it is rejected. That is the reason the two objects are used together: the LimitRange supplies the defaults, then the quota counts them.

LimitRangeResourceQuota
ScopeOne container, Pod or claim at a timeThe total of the namespace
Can fill in missing valuesYes (default, defaultRequest)No, it only counts and refuses
Typical errormaximum cpu usage per Container is 1, but limit is 2exceeded quota: compute, requested: limits.memory=1Gi, used: limits.memory=7680Mi, limited: limits.memory=8Gi
Create it withA manifest (there is no kubectl create limitrange)kubectl create quota, or a manifest
Under the hood · Newer ways to set and change limits

Two features that are newer than most study material:

  • Resizing a running Pod. For a long time a Pod's resources could not be changed after creation. Since Kubernetes v1.35 in-place resize is stable: CPU and memory requests and limits of a running Pod can be changed through the resize subresource, without recreating the Pod:

    kubectl patch pod web --subresource resize --patch \
      '{"spec":{"containers":[{"name":"web","resources":{"limits":{"memory":"512Mi"}}}]}}'
    

    A resize cannot change the Pod's QoS class, and a container's resizePolicy can ask for a restart when memory changes. A plain kubectl edit pod of the resources is still refused; only the subresource accepts the change.

  • Pod-level resources. Recent versions also accept spec.resources on the Pod itself, a shared budget for all its containers together, in addition to the per-container values.

For the exam, per-container limits and changing them through the workload's Pod template remain the standard way.

Using it

Example · Add limits to a Pod quickly

kubectl run has no flag for limits. Generate the manifest and let kubectl set resources fill in the block, so you do not have to type the indentation by hand:

kubectl run web --image=nginx:1.29-alpine --dry-run=client -o yaml \
  | kubectl set resources --local -f - \
      --requests=cpu=250m,memory=128Mi --limits=cpu=500m,memory=256Mi -o yaml > web.yaml
kubectl apply -f web.yaml

Check what the API server stored and which class the Pod received:

kubectl get pod web -o jsonpath='{.spec.containers[0].resources}{"\n"}{.status.qosClass}{"\n"}'
{"limits":{"cpu":"500m","memory":"256Mi"},"requests":{"cpu":"250m","memory":"128Mi"}}
Burstable

Example · Find and fix an OOMKilled container

The Pod hungry keeps restarting:

kubectl get pod hungry
NAME     READY   STATUS             RESTARTS      AGE
hungry   0/1     CrashLoopBackOff   4 (20s ago)   2m

CrashLoopBackOff only says "it keeps stopping". The reason is in the container's last state:

kubectl describe pod hungry | grep -A 4 "Last State"
    Last State:     Terminated
      Reason:       OOMKilled
      Exit Code:    137

Exit code 137 is 128 + 9: the process was ended with signal 9 (SIGKILL). Together with the reason OOMKilled it means the container crossed its memory limit. Compare the limit with what the application needs:

kubectl get pod hungry -o jsonpath='{.spec.containers[0].resources}'     # {"limits":{"memory":"64Mi"},...}
kubectl top pod hungry --containers                                      # usage just before the kill, if metrics-server runs

Raise the limit. For a bare Pod, export it, change the value and recreate it:

kubectl get pod hungry -o yaml > hungry.yaml     # set limits.memory: 256Mi
kubectl replace --force -f hungry.yaml

If the Pod belongs to a Deployment, change the template instead; a rollout replaces the Pods:

kubectl set resources deployment hungry --limits=memory=256Mi
kubectl rollout status deployment hungry

Example · Give a namespace default limits

Every container in shop that sets nothing should get a 100m / 128Mi request and a 500m / 256Mi limit, and nobody may ask for more than 1 CPU. Apply the LimitRange shown above, then prove that it works:

kubectl apply -f limitrange.yaml
kubectl -n shop describe limitrange container-limits
Type        Resource  Min   Max  Default Request  Default Limit  Max Limit/Request Ratio
----        --------  ---   ---  ---------------  -------------  -----------------------
Container   cpu       50m   1    100m             500m           -
Container   memory    32Mi  1Gi  128Mi            256Mi          -
kubectl -n shop run plain --image=nginx:1.29-alpine
kubectl -n shop get pod plain -o jsonpath='{.spec.containers[0].resources}'
{"limits":{"cpu":"500m","memory":"256Mi"},"requests":{"cpu":"100m","memory":"128Mi"}}

The Pod was created without resources, and the stored object has them. kubectl describe pod plain also shows an annotation that names the LimitRanger plugin and the values it set.

Example · Find out why a Deployment has too few Pods

kubectl -n shop get deploy api shows 1/3 ready, and there are no Pending Pods. The missing Pods were refused at admission, so they do not exist and have no events of their own. The ReplicaSet that tried to create them holds the reason:

kubectl -n shop describe rs -l app=api | grep -A 3 Events
Warning  FailedCreate  replicaset-controller  Error creating: pods "api-7c9d8-x2x4q" is forbidden:
exceeded quota: compute, requested: limits.memory=1Gi, used: limits.memory=7680Mi, limited: limits.memory=8Gi

The namespace's limits already add up to 7680Mi of the 8Gi allowed, so another 1Gi does not fit. Lower the limit in the Deployment, scale something else down, or raise the quota:

kubectl -n shop describe quota compute            # Used and Hard, side by side
kubectl -n shop set resources deployment api --limits=memory=128Mi

Tricks

Common mistakes

  • Expecting a CPU limit to kill the container. CPU is throttled, never killed. A container that restarts was not stopped by its CPU limit; look at memory, probes or the application itself.
  • Thinking limits affect scheduling. Only requests do. The exception is a container with a limit and no request, where the request is set equal to the limit.
  • Writing memory: 256m. That is a quarter of a byte. Use Mi or Gi.
  • Putting resources under the Pod spec by habit. Limits belong to each container: spec.containers[].resources.limits.
  • Creating a LimitRange and expecting running Pods to change. It only acts on Pods created afterwards. Restart the workload to pick it up.
  • Editing the limits of a running Pod with kubectl edit pod. That is refused. Change the Deployment's template, recreate the Pod with kubectl replace --force -f, or use the resize subresource on a recent cluster.
  • Reading default in a LimitRange as "default request". It is the default limit.
  • Setting a very low memory limit "to be safe". A limit below what the application needs at start gives an endless OOMKilled loop. Measure first (kubectl top pod --containers), then set the limit with some headroom.

Recap

  • A limit is the most a container may use; a request is what is reserved for it. Both live under spec.containers[].resources.
  • The kubelet passes limits to the runtime, which writes them into the container's cgroup; the kernel enforces them.
  • Over the CPU limit the container is throttled. Over the memory limit it is OOMKilled (exit code 137) and restarted in place.
  • The scheduler ignores limits, so limits on a node can exceed its capacity. Requests and limits together give the Pod its QoS class.
  • A LimitRange sets per-container defaults, minimums and maximums; a ResourceQuota caps the namespace total. Both act at admission, on new Pods only.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Read why a container is killed over and over, give it a limit it can live with, and set memory defaults and a ceiling for a whole namespace.

    Fix · Level 2 · standard · target 15 min

  • Section capstone on a three-node cluster. Reserve a node for one team, keep a search engine on fast disks, run an agent on every node whatever its taints, set resource defaults for a namespace, and place a Pod no scheduler will take.

    Build · Level 3 · challenge · target 35 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.