Skip to content

Kubernetes ResourceQuota and LimitRange: govern namespace capacity

Set a namespace-wide ResourceQuota, add LimitRange defaults so existing workloads still get admitted, use object-count and per-StorageClass quotas and scope selectors, and read kubectl describe quota.

ResourceQuota and LimitRange are two different objects that people routinely confuse, and using either one alone tends to break something. A quota is a namespace-wide ceiling: the sum of everything in the namespace may not exceed the numbers in spec.hard, and the API server refuses the object that would push you over. A LimitRange works one object at a time: it injects default requests and limits into containers that declare none, and rejects containers asking for more — or less — than you allow. The trap that catches most teams is that the moment a quota names requests.cpu or limits.memory, every pod entering that namespace must declare that field or be rejected outright. A LimitRange with sensible defaults is what keeps the existing deployments alive on the day the quota lands.

What you’ll accomplish

  • Tell apart a namespace ceiling (ResourceQuota) from per-object defaults and bounds (LimitRange), and apply them in the right order.
  • Read the two admission errors a reader will actually hit: must specify limits.cpu and exceeded quota.
  • Cap object counts (pods, services, persistentvolumeclaims, count/deployments.apps) and storage per StorageClass.
  • Narrow a quota with scope selectors — BestEffort, NotTerminating, PriorityClass.
  • Read kubectl describe quota and know what to do when used has already passed hard.

Prerequisites

  • A Kubernetes cluster on 1.28 or newer. Both objects are long-stable in the core v1 API; nothing here depends on a feature gate.
  • The ResourceQuota and LimitRanger admission plugins enabled on the API server. Both are in the default enabled set for kubeadm and every managed distribution worth using, so you normally have them already.
  • kubectl with permission to create ResourceQuota and LimitRange objects in the target namespace, plus get on pods, events and replicasets there.
  • A scratch namespace. Applying a quota to a busy namespace with no LimitRange in place will stop every rollout in it.
  • A working understanding of what a request and a limit actually do. If requests versus limits is still fuzzy, read CPU and memory requests versus limits first — quota arithmetic is entirely in those units.

How it works

Both objects are enforced at admission, before anything reaches etcd or the scheduler. The order matters more than any other detail in this guide. LimitRanger runs twice: once in the mutating phase, where it writes defaults into containers that left resources empty, and again in the validating phase, where it checks min, max and maxLimitRequestRatio. ResourceQuota runs afterwards, in the validating phase, and by then every container has concrete numbers to count.

Flow diagram of pod admission: kubectl apply, then LimitRanger mutating phase injecting defaults, then LimitRanger validating phase enforcing min and max, then ResourceQuota checking used plus the new pod against hard, then the scheduler, with rejection branches at the two enforcement gates

That sequence is why the two objects are a pair. A quota that names any compute resource makes the matching pod field mandatory: put requests.cpu in spec.hard and every container must set a CPU request, because the quota accountant cannot add up a value that does not exist. Without a LimitRange, that requirement is retroactively imposed on YAML written months earlier, and the whole namespace stops accepting new pods. With one, the missing fields are filled in before the quota ever looks.

A quota counts more than compute. spec.hard accepts object counts (pods, services, secrets, configmaps, persistentvolumeclaims, services.loadbalancers, services.nodeports), the generic count/<resource>.<group> form for anything else (count/deployments.apps, count/cronjobs.batch), total storage (requests.storage), and per-StorageClass storage using the <class>.storageclass.storage.k8s.io/requests.storage key. Note that cpu and memory in spec.hard are aliases for requests.cpu and requests.memory, not for the limits.

Scopes narrow what a quota counts. BestEffort matches only pods with no requests or limits at all, NotBestEffort the rest; Terminating matches pods with activeDeadlineSeconds set, NotTerminating those without; PriorityClass matches by class name and needs the scopeSelector form. Several quotas may exist in one namespace, and a pod must satisfy every one whose scope it falls into.

Finally, both objects apply only at admission time. Creating a quota does not evict anything that already exists — it simply records the existing consumption in status.used, which is how a namespace can legitimately sit above its own ceiling.

Step-by-step

1. Measure before you set a number. A quota picked out of the air either blocks everything or constrains nothing. Sum what the namespace requests today:

kubectl get pods -n team-a \
  -o custom-columns=NAME:.metadata.name,CPU:.spec.containers[*].resources.requests.cpu,MEM:.spec.containers[*].resources.requests.memory
NAME                        CPU     MEM
api-6d4f7c9b8-2xkqp         500m    512Mi
api-6d4f7c9b8-8mzvr         500m    512Mi
worker-5c9d84f6d-jt4kx      <none>  <none>

Every <none> is a pod that will be rejected the instant a compute quota exists. That column is the real reason to do step 2 first.

2. Create the LimitRange first. This is the whole trick. Defaults land before the quota is ever written:

apiVersion: v1
kind: LimitRange
metadata:
  name: team-a-defaults
  namespace: team-a
spec:
  limits:
    - type: Container
      defaultRequest:
        cpu: 100m
        memory: 128Mi
      default:
        cpu: 500m
        memory: 512Mi
      min:
        cpu: 50m
        memory: 64Mi
      max:
        cpu: "2"
        memory: 2Gi
      maxLimitRequestRatio:
        cpu: "4"
kubectl apply -f team-a-limitrange.yaml
kubectl describe limitrange team-a-defaults -n team-a
Name:       team-a-defaults
Namespace:  team-a
Type        Resource  Min   Max  Default Request  Default Limit  Max Limit/Request Ratio
----        --------  ---   ---  ---------------  -------------  -----------------------
Container   cpu       50m   2    100m             500m           4
Container   memory    64Mi  2Gi  128Mi            512Mi          -

type also accepts Pod, which bounds the sum across a pod’s containers but takes no defaults, and PersistentVolumeClaim, where min and max apply to storage. If you set default without defaultRequest, the request is set equal to the default limit — usually not what you want, since it reserves the full ceiling on every pod.

3. Confirm the defaults are actually injected. Create a pod with an empty resources block and read back what the API server stored:

kubectl run limit-probe -n team-a --image=registry.k8s.io/pause:3.9 --restart=Never
kubectl get pod limit-probe -n team-a -o jsonpath='{.spec.containers[0].resources}{"\n"}'
{"limits":{"cpu":"500m","memory":"512Mi"},"requests":{"cpu":"100m","memory":"128Mi"}}

If that comes back as {}, the LimitRange is in a different namespace or LimitRanger is not in the admission chain. Stop here and fix it — the rest of the guide depends on it.

4. Apply the compute quota. Only now:

apiVersion: v1
kind: ResourceQuota
metadata:
  name: compute-resources
  namespace: team-a
spec:
  hard:
    requests.cpu: "4"
    requests.memory: 16Gi
    limits.cpu: "8"
    limits.memory: 16Gi
    pods: "20"
kubectl apply -f team-a-quota.yaml
resourcequota/compute-resources created

5. Meet the two rejection messages. These are the errors you will spend your support time explaining. First, a pod that skips a field the quota tracks, in a namespace with no LimitRange to cover it:

Error from server (Forbidden): error when creating "pod.yaml": pods "api" is
forbidden: failed quota: compute-resources: must specify limits.cpu for: app;
limits.memory for: app; requests.cpu for: app; requests.memory for: app

Second, a pod that is well-formed but does not fit under the ceiling:

Error from server (Forbidden): error when creating "pod.yaml": pods "api" is
forbidden: exceeded quota: compute-resources, requested: requests.cpu=1,
used: requests.cpu=3800m, limited: requests.cpu=4

Both are Forbidden from the API server, not scheduling failures. Nothing is Pending; the object simply never exists.

6. Add object-count and storage quotas. These are separate objects so you can change one without touching the compute budget:

apiVersion: v1
kind: ResourceQuota
metadata:
  name: object-counts
  namespace: team-a
spec:
  hard:
    persistentvolumeclaims: "10"
    services: "15"
    services.loadbalancers: "2"
    secrets: "40"
    count/deployments.apps: "12"
    count/cronjobs.batch: "6"
    requests.storage: 500Gi
    fast-ssd.storageclass.storage.k8s.io/requests.storage: 200Gi
    fast-ssd.storageclass.storage.k8s.io/persistentvolumeclaims: "5"
kubectl apply -f team-a-objects.yaml
kubectl get resourcequota -n team-a
NAME                AGE   REQUEST                                                     LIMIT
compute-resources   4m    pods: 14/20, requests.cpu: 3800m/4, requests.memory: 12Gi/16Gi   limits.cpu: 6/8, limits.memory: 18Gi/16Gi
object-counts       9s    persistentvolumeclaims: 5/10, services: 4/15                 

services.loadbalancers is the one worth setting on day one: each one is a cloud load balancer somebody has to pay for, and a stray Helm value can create several.

7. Scope a quota so it only counts part of the namespace. Two useful shapes. A cap on pods with no resources declared at all:

apiVersion: v1
kind: ResourceQuota
metadata:
  name: besteffort-cap
  namespace: team-a
spec:
  hard:
    pods: "5"
  scopes:
    - BestEffort

And a quota that only applies to long-running work, letting short jobs through untouched — plus the scopeSelector form needed for PriorityClass:

apiVersion: v1
kind: ResourceQuota
metadata:
  name: long-running
  namespace: team-a
spec:
  hard:
    requests.cpu: "3"
    pods: "12"
  scopes:
    - NotTerminating
---
apiVersion: v1
kind: ResourceQuota
metadata:
  name: critical-tier-cap
  namespace: team-a
spec:
  hard:
    pods: "4"
  scopeSelector:
    matchExpressions:
      - scopeName: PriorityClass
        operator: In
        values: ["critical-tier"]

The PriorityClass scope is the only mechanism that stops any namespace from claiming a high-value class — see PriorityClass and preemption for what that class buys once a pod has it. Note the BestEffort scope can only quota pods; adding requests.cpu to it is rejected, since a BestEffort pod has no requests by definition.

8. Read the budget. kubectl describe quota is the one command to teach the team:

kubectl describe quota compute-resources -n team-a
Name:            compute-resources
Namespace:       team-a
Resource         Used   Hard
--------         ----   ----
limits.cpu       6      8
limits.memory    18Gi   16Gi
pods             14     20
requests.cpu     3800m  4
requests.memory  12Gi   16Gi

Horizontal bar chart of a namespace budget showing used against hard for requests.cpu, requests.memory, limits.cpu, limits.memory, pods and persistentvolumeclaims, with the limits.memory row already over its ceiling

limits.memory at 18Gi against a hard of 16Gi is not a bug. The quota was created after those pods existed, so it recorded reality. Nothing is evicted, but every new pod in the namespace is refused until usage drops back under the ceiling.

Validate it works

A pod with no resources block is admitted and carries the defaults. This is the check that proves the ordering is right:

kubectl run quota-check -n team-a --image=registry.k8s.io/pause:3.9 --restart=Never
kubectl get pod quota-check -n team-a \
  -o jsonpath='{.spec.containers[0].resources.requests.cpu}{"\n"}'
100m

The quota accounting moved. Compare used before and after that pod:

kubectl get resourcequota compute-resources -n team-a -o jsonpath='{.status.used}{"\n"}'
{"limits.cpu":"6100m","limits.memory":"18Gi","pods":"15","requests.cpu":"3900m","requests.memory":"12Gi"}

A container over max is refused, with the LimitRange message and not the quota one. Ask for 4 CPUs against a max of 2:

kubectl run too-big -n team-a --image=registry.k8s.io/pause:3.9 --restart=Never \
  --overrides='{"spec":{"containers":[{"name":"too-big","image":"registry.k8s.io/pause:3.9","resources":{"limits":{"cpu":"4"}}}]}}'
Error from server (Forbidden): pods "too-big" is forbidden: maximum cpu usage
per Container is 2, but limit is 4.

Troubleshooting

  • A Deployment applies cleanly but no pods appear. kubectl apply creates the Deployment object, which is not subject to a compute quota; the ReplicaSet controller is what gets refused when it tries to create pods, and its failure never reaches your terminal. Look at the ReplicaSet, not the Deployment: kubectl describe rs -n team-a shows Warning FailedCreate ... error creating: pods "api-6d4f7c9b8-" is forbidden: exceeded quota: compute-resources. The controller retries with backoff, so the event repeats and the rollout simply stalls.
  • must specify requests.cpu even though a LimitRange exists. Three usual causes. The LimitRange is in another namespace — both objects are namespaced and neither one is inherited. Or its type is Pod rather than Container, and Pod entries carry no defaults. Or the container sets some fields, in which case only the missing ones are defaulted, and a container that sets limits.memory alone still needs a CPU limit if the quota tracks limits.cpu. Confirm with the describe limitrange table from step 2.
  • used is stuck above hard and nothing can be created. Expected when a quota is applied to a populated namespace. Either raise hard to the current number and lower it in stages, or scale a workload down to free room. Watch it fall with kubectl get resourcequota compute-resources -n team-a -w. Note that terminating pods still count until they are fully gone.
  • used looks wrong or lags. The quota controller recomputes usage periodically as well as at admission, so a brief drift after a burst of deletions is normal. If a number stays wrong for minutes, the usual cause is a resource the controller cannot resolve — a count/<resource>.<group> key naming a CRD that was uninstalled. Delete the stale key from spec.hard.
  • A PriorityClass-scoped quota does not seem to apply. scopeSelector matches on the resolved class name, so a pod that never set priorityClassName falls outside it entirely and is counted only by unscoped quotas. Verify with kubectl get pods -n team-a -o custom-columns=NAME:.metadata.name,CLASS:.spec.priorityClassName. Also check that no other quota in the namespace is the one actually rejecting the pod — the error message always names which quota refused.
  • Everything is allowed even though the quota exists. Check the object was accepted with kubectl get resourcequota -n team-a, then check status.hard is populated, then confirm the ResourceQuota admission plugin is enabled on the API server. A quota object with an empty status is a strong hint that the plugin is off.

When this is the wrong approach

Quota is a spend ceiling and an admission control, not a scheduler and not an isolation boundary.

  • It does not reserve capacity. Granting a namespace requests.cpu: 100 when the cluster has 40 cores allocatable simply means pods are admitted and then sit Pending. Quota sold against capacity you do not have moves the failure later and makes it harder to read.
  • It does not stop a container from using what it did not ask for. A pod within quota can still consume idle CPU on its node and starve a neighbour, because quota governs the sum of declared requests and limits, not runtime behaviour. Node-level isolation comes from correct requests, not from quota.
  • It is not multi-tenancy. A namespace with a quota is still one API surface with shared nodes, a shared network and shared CRDs. If tenants do not trust each other, you need separate clusters or a purpose-built multi-tenancy layer, not a number in spec.hard.
  • It is a poor fit for bursty batch work. A quota is a hard wall with no queue behind it: over the line, the job is refused and it is the submitting controller’s problem. Batch systems that need admission ordering want a queueing layer that understands their workloads.
  • A LimitRange is not a policy engine. It bounds compute resources and PVC storage on individual objects, and that is all. Rules about images, labels, security context or required annotations belong in a validating admission policy or an admission webhook.

The reference material worth keeping open is the Kubernetes resource quotas documentation, which lists every quotable resource name and scope, and the limit ranges documentation for exactly how defaults are applied.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.