⚡ ~/naveed Interview Prep
⚡ Portfolio Home 👤 About Naveed Bio & Credentials 📫 Contact Naveed Get In Touch ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →
← Back to All Kubernetes Interview Questions Scenario 138 of 207 in Kubernetes
Senior DevOps / SRE [L2] Kubernetes Additional Kubernetes Scenarios (Q101-Q200) Production Scenario [L2]
🎯 Target Role / Context: Kubernetes Scenario #128 (L2) · Additional Kubernetes Scenarios (Q101-Q200)

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.

#Kubernetes #L2 #Container Orchestration #K8s
🎙️ Candidate Opening & Architectural Context
"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."
Advertisement
⚡ Recommended Practice Lab

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.

1️⃣

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.cpu or limits.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.
Pro Tip: LimitRange is friendly (it fixes the pod), quota is a budget, and admission policy is the strict gatekeeper.
2️⃣

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: default sets limits, defaultRequest sets requests.
  • Bounds: min and max reject containers outside the range.
  • Quota fields: use requests.cpu, requests.memory, limits.cpu, limits.memory and pods.
  • 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.
Advertisement
3️⃣

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 ValidatingAdmissionPolicyBinding scopes the policy to namespaces by label selector and sets validationActions (Warn, Audit, Deny).
  • Roll out safely: start with Warn and Audit, review the results, then switch to Deny.
  • 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.
4️⃣

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=server shows 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 prod shows 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=server against 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.
5️⃣

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 apply output.
  • 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.
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"Pro-Tip: Deployments are not rejected at apply time when a pod violates quota or policy. Check <code>kubectl describe rs</code> events for the real error."
⚡ 60-Second Elevator Pitch Talking Points
  • 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.
⛔ Critical Candidate Mistakes to Avoid in This Scenario

Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:

  1. Relying on LimitRange alone as an enforcement mechanism It only injects defaults and bounds; it does not force teams to think about sizing.
  2. 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.
  3. Enabling Deny without an audit pass Existing workflows break on the next rollout and you only find out when pods fail to be recreated.
  4. Forgetting init containers in the CEL rule Init containers can consume resources without limits if only spec.containers is checked.
Advertisement
📥 FREE DOWNLOAD · 101-PAGE COMPANION HANDBOOK
Studying for Kubernetes & SRE Technical Rounds?
Download the complete 100-question PDF field guide covering all 11 core modules with offline diagnostic runbooks.
📥 Download PDF (Free) Read Online Guide →
Want more Kubernetes scenarios?
Explore our complete collection of scenario-based Kubernetes interview runbooks.
Browse All Kubernetes Questions →