Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 78 ยท Scheduling and Scaling

Namespaces, Quotas and Limit Ranges

Split a cluster with namespaces, cap each team with ResourceQuota, set per-container defaults with LimitRange, and avoid the default-namespace traps.

A cluster is usually shared: several teams, several environments, dozens of applications. If everything lived in one flat list, names would collide (db, web, config ...), one team could delete another's objects by accident, and a single runaway Deployment could eat all the CPU. Namespaces are Kubernetes' way of carving one cluster into named, separate areas. ResourceQuota and LimitRange then put limits on what each area may consume.

This lesson explains what a namespace is and, importantly, what it is not, then shows how quotas are enforced at admission time and how limit ranges fill in defaults.

One cluster, many areas

Namespaces Scope for names, RBAC and policies.
ResourceQuota A budget for the whole namespace.
LimitRange Defaults and bounds per container.
1 / 2

What namespaces give you

Every cluster starts with four namespaces: default (where objects go if you say nothing), kube-system (the cluster's own components), kube-public (readable by everyone, rarely used) and kube-node-lease (node heartbeats). You create your own:

CONSOLE
$ kubectl create namespace staging
namespace/staging created
$ kubectl get namespaces
$ kubectl get pods -n staging
$ kubectl get pods --all-namespaces      # or -A

A namespace provides three things:

  1. Name scope. Names must be unique within a namespace, not across the cluster. web can exist in staging and in production.
  2. A boundary for policy. RBAC roles and bindings, quotas, limit ranges and network policies are all attached to namespaces. See Authentication and RBAC.
  3. Bulk operations. kubectl delete namespace staging removes everything inside it. That is convenient and dangerous in equal measure.

Not every object lives in a namespace. Nodes, PersistentVolumes, StorageClasses, ClusterRoles and the namespaces themselves are cluster-scoped. kubectl api-resources --namespaced=false lists them.

Service names across namespaces

Services get a DNS name that includes the namespace: <service>.<namespace>.svc.cluster.local. From a pod in the same namespace the short name db works. To reach another namespace you add the namespace: db.production. This is why the same service name can exist twice without clashing (more in DNS and Service Discovery).

Working in a namespace without typing -n

Most kubectl commands use the namespace of your current context. You can pass -n every time, or change the context's default:

CONSOLE
$ kubectl config set-context --current --namespace=staging
$ kubectl config view --minify | grep namespace
    namespace: staging

You can also put metadata.namespace in a manifest. If you do and also pass a different -n, kubectl stops with an error rather than guess.

The default namespace pitfalls

  • Everything lands in default when you forget -n. After a few weeks default is a junk drawer. Treat it as a scratch area at most, and give each app its own namespace.
  • You looked in the wrong namespace. "My pod disappeared" often means you are looking at the wrong one. kubectl get pods -A | grep name finds it.
  • Cleaning up deletes everything. Deleting a namespace deletes every namespaced object in it, including PersistentVolumeClaims. Whether the data behind them survives depends on the reclaim policy of the volumes (see PersistentVolumes and Claims).
  • A namespace stuck in Terminating usually means some object inside has a finalizer that nobody is processing, for example a custom resource whose operator was already removed. Find what is left with kubectl api-resources --verbs=list --namespaced -o name, then kubectl get each one.
  • A false sense of security. Two namespaces can reach each other over the pod network unless you add network policies, and a pod in any namespace can sit on any node.

ResourceQuota: a budget for a namespace

A ResourceQuota caps the total of something in one namespace. It can limit compute (requests.cpu, requests.memory, limits.cpu, limits.memory), storage (requests.storage, per StorageClass as well), and object counts (pods, services, persistentvolumeclaims, count/deployments.apps, secrets, ...).

YAML
apiVersion: v1
kind: ResourceQuota
metadata:
  name: team-budget
  namespace: staging
spec:
  hard:
    pods: "20"
    requests.cpu: "4"
    requests.memory: 8Gi
    limits.cpu: "8"
    limits.memory: 16Gi
    persistentvolumeclaims: "5"
CONSOLE
$ kubectl describe quota team-budget -n staging
Name:            team-budget
Namespace:       staging
Resource         Used   Hard
--------         ----   ----
limits.cpu       1500m  8
pods             3      20
requests.cpu     600m   4

Quota is enforced by an admission plugin: when a request to create an object arrives, the API server adds up what the namespace already uses, and if the new object would push a total over the hard limit, the request is rejected with 403 Forbidden and a message such as exceeded quota: team-budget, requested: requests.cpu=300m, used: requests.cpu=300m, limited: requests.cpu=500m. Quota does not touch objects that already exist, so lowering a quota below current usage does not kill anything; it only blocks new creations.

A rule you must know: if a quota covers CPU or memory, every new pod must declare that resource. A pod with no requests.cpu is rejected, because the quota system has nothing to count. This is exactly where a LimitRange helps.

LimitRange: defaults and bounds per container

A LimitRange sets rules for individual containers, pods or claims in a namespace:

YAML
apiVersion: v1
kind: LimitRange
metadata:
  name: container-defaults
  namespace: staging
spec:
  limits:
    - type: Container
      defaultRequest:      # used when the container sets no request
        cpu: 100m
        memory: 128Mi
      default:             # used when the container sets no limit
        cpu: 500m
        memory: 256Mi
      max:                 # no container may ask for more
        cpu: "2"
        memory: 1Gi
      min:
        cpu: 50m

Its admission step runs before the quota check. It first fills in missing requests and limits from defaultRequest and default, then validates against min, max and maxLimitRequestRatio. Pods that break a bound are rejected; pods that set nothing are given values and then counted against the quota. LimitRange also handles type: Pod (totals across containers) and type: PersistentVolumeClaim (storage size bounds). Defaults apply to pods created after the LimitRange exists, so existing pods are unchanged. Background on requests and limits is in Resource Requests and Limits.

Try it: a LimitRange and quota admission check

This stand-in mimics the order of the real admission chain: defaults first, then bounds, then the namespace quota. Pods are admitted one after the other.

Python LimitRange defaults, then ResourceQuota

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pod a declares nothing, so it receives the default request of 100m CPU and 128 MiB. Pod b fits. Pod c would raise total CPU requests to 600m and is refused by the quota. Pod d is rejected earlier, by the LimitRange, for asking for a 4-CPU limit. Pod e is small enough to fit into what is left. The final line shows the budget consumed: 400m CPU, 292 MiB of memory and 3 pods, which is the quota's pod limit.

Quota and controllers: errors appear late

A subtle behavior surprises almost everyone once. Quota is checked when a pod is created, not when a Deployment is. If the namespace is full, kubectl apply of a Deployment still succeeds, because the Deployment object itself is not what the quota counts. The ReplicaSet then tries to create pods and each attempt fails:

CONSOLE
$ kubectl get deployment web
NAME   READY   UP-TO-DATE   AVAILABLE
web    4/6     4            4
$ kubectl describe rs web-7d9
Warning  FailedCreate  replicaset-controller  Error creating: pods "web-7d9-x2k4q" is forbidden: exceeded quota: ...

The error is in the ReplicaSet's events, not in the output of kubectl apply. The next TryIt reproduces that picture, and also shows the same service name living in two namespaces:

Python Deployment accepted, pods forbidden

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When a rollout seems stuck at "4/6", kubectl describe the ReplicaSet (not only the Deployment) and look for FailedCreate. See Deployments.

Multi-tenancy: how far do namespaces go?

For teams that trust each other, a namespace per team or per app plus RBAC, quotas, limit ranges and default-deny network policies is a solid "soft" multi-tenancy model. For tenants that do not trust each other (customers, for example), namespaces alone are not enough: all pods share the nodes' kernels, cluster-scoped resources such as CRDs are shared, and a noisy neighbor can still hurt via the API server. Stronger isolation means separate node pools (using the taints from the previous lesson), sandboxed runtimes, virtual clusters, or separate clusters. Cost, Reliability and Multi-Cluster returns to this.

What is real and what is the stand-in: all YAML and kubectl output above is the real thing but read-only here, since the site has no cluster. The Python admission check follows the same order as the API server (LimitRange defaults, bounds, quota) with simplified unit parsing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these objects is cluster-scoped, not namespaced?

    PersistentVolumes (like Nodes, StorageClasses and ClusterRoles) belong to the whole cluster. PersistentVolumeClaims, in contrast, are namespaced.
  2. 2. A namespace has a ResourceQuota for requests.cpu. A pod is submitted with no CPU request and there is no LimitRange. What happens?

    Quota cannot count an undeclared resource, so the API server rejects the pod. A LimitRange with defaultRequest would fill the value in first.
  3. 3. A Deployment asks for 6 replicas, but the namespace quota allows only 4 pods. What do you see?

    Quota is enforced when the ReplicaSet creates each pod, so the Deployment object itself is accepted and the errors appear as events.
  4. 4. Which statement about namespaces is correct?

    Names are scoped to the namespace. Networking is open by default, nodes are shared, and deleting a namespace removes every namespaced object in it.

Summary

  • Namespaces scope names and attach policy (RBAC, quotas, network policies); they are not a security or network boundary by themselves.
  • Some objects (Nodes, PersistentVolumes, StorageClasses, ClusterRoles) are cluster-scoped.
  • A ResourceQuota caps compute, storage and object counts per namespace and is checked at admission; it never affects existing objects.
  • If a quota covers CPU or memory, pods must declare them; a LimitRange supplies defaults and enforces min/max.
  • Quota errors for Deployments show up as FailedCreate events on the ReplicaSet.
  • Avoid dumping everything into default; set a namespace in your context.

Next: make replica counts follow the load in Horizontal Pod Autoscaler.