ResourceQuotas & LimitRanges
On a shared cluster one team's runaway Deployment shouldn't starve everyone else. Two namespace-level objects keep things fair:
| Object | Limits | Checked when |
|---|---|---|
| ResourceQuota | The total a namespace may use (sum of requests/limits, number of objects) | Each create/update; over-quota requests are rejected |
| LimitRange | Defaults and min/max per container (or per Pod/PVC) | Each Pod creation; fills in defaults, rejects out-of-range values |
Both are enforced by admission controllers in the API server, before anything is stored.
ResourceQuota
apiVersion: v1
kind: ResourceQuota
metadata:
name: team-shop
namespace: shop
spec:
hard:
requests.cpu: "8"
requests.memory: 16Gi
limits.memory: 32Gi
pods: "40"
services.loadbalancers: "1"
persistentvolumeclaims: "10"
requests.storage: 200Gikubectl describe resourcequota team-shop -n shopSample output:
Name: team-shop
Namespace: shop
Resource Used Hard
-------- ---- ----
limits.memory 12Gi 32Gi
persistentvolumeclaims 3 10
pods 17 40
requests.cpu 5500m 8
requests.memory 9Gi 16Gi
services.loadbalancers 1 1A model of the quota admission check. Each new Pod's requests are added to the namespace's usage; if any total would exceed its hard limit, the request is rejected with a 403 Forbidden: exceeded quota error:
hard = {"requests.cpu": 2000, "requests.memory": 4096, "pods": 4} # millicores, MiB, count
used = {"requests.cpu": 0, "requests.memory": 0, "pods": 0}
def admit(name, cpu, mem):
wanted = {"requests.cpu": cpu, "requests.memory": mem, "pods": 1}
over = [k for k in hard if used[k] + wanted[k] > hard[k]]
if over:
details = ", ".join(f"{k}: used {used[k]}, requested {wanted[k]}, limited {hard[k]}" for k in over)
return f"{name}: Error forbidden: exceeded quota: team-shop ({details})"
for k in hard:
used[k] += wanted[k]
return f"{name}: created"
for name, cpu, mem in [("api-1", 500, 1024), ("api-2", 500, 1024), ("worker", 1000, 1024), ("api-3", 500, 512)]:
print(admit(name, cpu, mem))
print("usage:", used)api-1: created
api-2: created
worker: created
api-3: Error forbidden: exceeded quota: team-shop (requests.cpu: used 2000, requested 500, limited 2000)
usage: {'requests.cpu': 2000, 'requests.memory': 3072, 'pods': 3}
Note: If a quota covers
requests.cpu(or memory), every new Pod in the namespace must specify that request, otherwise it is rejected. That's why quotas are almost always paired with a LimitRange that supplies defaults.
With a Deployment, a rejected Pod doesn't make kubectl apply fail: the Deployment is accepted, but its ReplicaSet can't create Pods. Look for FailedCreate events on the ReplicaSet (kubectl describe rs).
LimitRange
apiVersion: v1
kind: LimitRange
metadata:
name: defaults
namespace: shop
spec:
limits:
- type: Container
defaultRequest: {cpu: 100m, memory: 128Mi} # used when a request is missing
default: {memory: 256Mi} # default *limit*
min: {cpu: 50m, memory: 64Mi}
max: {cpu: "2", memory: 2Gi}The LimitRanger admission plugin first fills in missing values, then validates min/max:
limit_range = {
"defaultRequest": {"cpu": 100, "memory": 128},
"default": {"memory": 256},
"min": {"cpu": 50, "memory": 64},
"max": {"cpu": 2000, "memory": 2048},
}
def apply_limit_range(container):
req = dict(container.get("requests", {}))
lim = dict(container.get("limits", {}))
for res, value in limit_range["default"].items():
lim.setdefault(res, value)
for res, value in limit_range["defaultRequest"].items():
req.setdefault(res, value)
errors = []
for res, low in limit_range["min"].items():
if req.get(res, low) < low:
errors.append(f"minimum {res} usage per Container is {low}, but request is {req[res]}")
for res, high in limit_range["max"].items():
if lim.get(res, 0) > high:
errors.append(f"maximum {res} usage per Container is {high}, but limit is {lim[res]}")
return req, lim, errors
for name, c in {
"empty": {},
"custom": {"requests": {"cpu": 500, "memory": 512}, "limits": {"memory": 1024}},
"too small": {"requests": {"cpu": 10}},
"too big": {"limits": {"cpu": 4000, "memory": 4096}},
}.items():
req, lim, errors = apply_limit_range(c)
print(f"{name:9} requests={req} limits={lim}")
for e in errors:
print(" rejected:", e)empty requests={'cpu': 100, 'memory': 128} limits={'memory': 256}
custom requests={'cpu': 500, 'memory': 512} limits={'memory': 1024}
too small requests={'cpu': 10, 'memory': 128} limits={'memory': 256}
rejected: minimum cpu usage per Container is 50, but request is 10
too big requests={'cpu': 100, 'memory': 128} limits={'cpu': 4000, 'memory': 4096}
rejected: maximum cpu usage per Container is 2000, but limit is 4000
rejected: maximum memory usage per Container is 2048, but limit is 4096
(Units in the model: CPU in millicores, memory in MiB.)
Other quota scopes
- Object counts:
count/deployments.apps: "20",count/secrets: "50",configmaps: "30". - Priority classes: quotas can be scoped with
scopeSelectorto Pods of a given PriorityClass, e.g. limit how muchhigh-prioritycapacity a team may claim. - Storage per class:
fast.storageclass.storage.k8s.io/requests.storage: 100Gi.
Test yourself
What does a ResourceQuota limit?
- One container's memory
- The total resources and object counts of a namespace
- The size of a node
- Network bandwidth
A namespace has a requests.cpu quota but no LimitRange. A Pod without a CPU request is created. What happens?
- It gets 0 CPU
- It is rejected
- It is scheduled as BestEffort
- The quota is ignored
In a LimitRange, what does default set?
- The default request
- The default limit
- The minimum
- The namespace's quota