Q: How do you enforce that all pods in a namespace must have resource limits?
LimitRange with defaultRequest and default limits OR use OPA/Gatekeeper/Kyverno policy that rejects pods without resource limits.
Want to master this scenario in a live sandbox? KodeKloud's CKA & CKAD Hands-On Certification Track covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Direct Answer: To <strong>enforce that all pods in a namespace must have resource limits</strong>, combine a LimitRange (to inject defaults), a ResourceQuota (to cap the total and force every pod to declare values) and, where you need a hard rule, an admission policy such as ValidatingAdmissionPolicy or Kyverno. Each tool has a different strength: defaults, caps, and rejection. Interviewers ask to see whether you understand where each applies and how they interact at admission time.
Mental model: default, cap, then reject
Three layers solve three different problems, and a robust namespace usually uses more than one.
- LimitRange: sets default requests and limits, plus min, max and ratio, per container in a namespace. Pods without resources get the defaults at admission.
- ResourceQuota: caps the aggregate requests and limits for the namespace. If the quota covers
limits.cpuorlimits.memory, every new pod must specify them (or get them from a LimitRange), otherwise creation is rejected. - Admission policy: a ValidatingAdmissionPolicy (GA in 1.30) or a policy engine like Kyverno or OPA Gatekeeper can reject pods that omit limits explicitly, with a clear message.
- Scope: all of these act at creation time; they do not change pods that are already running.
- Why limits matter: pods without limits can consume all node memory or CPU, which leads to evictions and noisy-neighbour incidents and makes capacity planning guesswork.
- Requests versus limits: requests drive scheduling and QoS, limits cap runtime usage. Requiring both is the safest policy, and setting equal values gives Guaranteed QoS.
Hands-on: enforce resource limits for all pods with LimitRange and quota
Apply both objects to the namespace; together they guarantee that every container has values and the total stays bounded.
apiVersion: v1
kind: LimitRange
metadata:
name: container-defaults
namespace: prod
spec:
limits:
- type: Container
defaultRequest: {cpu: 100m, memory: 128Mi}
default: {cpu: 500m, memory: 256Mi}
max: {cpu: "2", memory: 2Gi}
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: ns-budget
namespace: prod
spec:
hard:
requests.cpu: "10"
requests.memory: 20Gi
limits.cpu: "20"
limits.memory: 40Gi
pods: "100"
- Defaults:
defaultsets limits,defaultRequestsets requests. - Bounds:
minandmaxreject containers outside the range. - Quota fields: use
requests.cpu,requests.memory,limits.cpu,limits.memoryandpods. - Order of operations: the LimitRanger admission step injects defaults first, so the quota check then sees complete values.
- Defaults are a policy choice: choose defaults conservatively. A tiny default memory limit produces OOMKills, while a huge one defeats the purpose.
Hard rejection with ValidatingAdmissionPolicy
When defaults are not acceptable and teams must declare limits themselves, reject pods that omit them.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: require-container-limits
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods"]
validations:
- expression: >-
object.spec.containers.all(c,
has(c.resources.limits) &&
'cpu' in c.resources.limits &&
'memory' in c.resources.limits)
message: "All containers must set cpu and memory limits."
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: require-container-limits-prod
spec:
policyName: require-container-limits
validationActions: ["Deny"]
matchResources:
namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: prod
- CEL expression: check every container, and init containers if you want full coverage, for the presence of cpu and memory limits.
- Binding: a
ValidatingAdmissionPolicyBindingscopes the policy to namespaces by label selector and setsvalidationActions(Warn,Audit,Deny). - Roll out safely: start with
WarnandAudit, review the results, then switch toDeny. - Interaction with LimitRange: mutating defaults are applied before validating policies run, so if you want pods without limits to fail, do not install a defaulting LimitRange in that namespace.
- Message quality: a clear deny message that tells developers what to add saves support requests, so include the exact missing field in the text.
Verify the enforcement and read the errors
Test with a deliberately bad pod and inspect what the cluster says.
kubectl -n prod run test --image=nginx --dry-run=server -o yaml | grep -A6 resources
kubectl -n prod describe resourcequota ns-budget
kubectl -n prod describe limitrange container-defaults
- Dry run:
kubectl run test --image=nginx -n prod --dry-run=servershows whether admission accepts or rejects. - Check defaults: create a pod without resources and run
kubectl get pod test -n prod -o jsonpath='{.spec.containers[0].resources}'to see injected values. - Quota usage:
kubectl describe quota ns-budget -n prodshows used versus hard. - Typical rejections: must specify limits.cpu from quota, maximum cpu usage per Container from LimitRange, or your policy message.
- Dry-run in CI: run
kubectl apply --dry-run=serveragainst a staging namespace in the pipeline so developers see rejections before deployment. - Existing violators: pods created before the policy keep running; they are only caught when recreated, so plan a controlled rollout restart after enabling enforcement.
Production practice: policy as code and coverage gaps
Make the rule apply everywhere and remain visible.
- Roll out via GitOps: keep LimitRange, quota and policies in the namespace template so every new namespace inherits them.
- Workloads that create pods: the quota and policy apply to the Pod at creation, not to the Deployment, so errors show in ReplicaSet events rather than
kubectl applyoutput. - Audit existing pods: list pods missing limits with a jq query before enabling Deny.
- Exceptions: exempt system namespaces through the binding's namespace selector.
- Alternative engines: Kyverno and OPA Gatekeeper offer richer mutation and reporting than CEL; pick one based on what your platform team already operates.
- I enforce limits with a LimitRange for defaults, a ResourceQuota for caps, and an admission policy for hard rejection.
- I verify with a server-side dry run and kubectl describe quota and limitrange.
- I ship these as namespace templates in GitOps and switch policy from Warn to Deny after auditing.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- Relying on LimitRange alone as an enforcement mechanism It only injects defaults and bounds; it does not force teams to think about sizing.
- Expecting kubectl apply of a Deployment to fail on quota violations The ReplicaSet fails to create pods, so the error appears in ReplicaSet events instead.
- Enabling Deny without an audit pass Existing workflows break on the next rollout and you only find out when pods fail to be recreated.
- Forgetting init containers in the CEL rule Init containers can consume resources without limits if only spec.containers is checked.