Kubernetes scheduling and resources in practice: requests, QoS, affinity, taints, priority, and in-place resize
Requests and limits, QoS classes, LimitRange and ResourceQuota, nodeSelector and affinity, anti-affinity and topologySpreadConstraints, taints, PriorityClass with preemption, Pending pods, and in-place resize, with real output from a kind cluster.
Kubernetes$ kubectl get pods -o wide▍When a pod is created, the kube-scheduler picks a node in two steps: it filters the nodes that can take it (free resources, taints, affinities) and scores the ones that remain. The most confusing detail is that it decides based on declared requests, not on actual usage. In this guide, we look at every lever that shapes that decision, tested on a kind cluster with Kubernetes 1.37: one control plane and two workers with 10 allocatable CPUs each, and no metrics-server. The c- prefix on names is just the lab’s convention.
Requests and limits
- requests: what the container has reserved. It’s what the scheduler adds up to decide whether the pod fits on the node.
- limits: the ceiling. Go over the CPU limit and the container gets throttled; go over the memory limit and it’s killed with
OOMKilled.
Requests that are too low overload the node; requests that are too high waste capacity and leave pods Pending. Set requests from observed usage and be careful with CPU limits, because throttling causes latency that’s hard to diagnose (see deep infrastructure troubleshooting).
QoS classes
The combination of requests and limits defines the pod’s QoS class, which matters when the node runs out of memory and the kubelet (or the kernel’s OOM killer) has to choose who goes:
| Class | Rule | Under memory pressure (in general) |
|---|---|---|
| Guaranteed | Every container has requests = limits for CPU and memory | Last in line |
| Burstable | At least one request or limit, without being Guaranteed | In the middle |
| BestEffort | No requests or limits at all | First |
apiVersion: v1
kind: Pod
metadata:
name: guaranteed
namespace: c-sched
spec:
containers:
- name: app
image: registry.k8s.io/pause:3.10
resources:
requests: { cpu: 250m, memory: 64Mi }
limits: { cpu: 250m, memory: 64Mi }
We also created a burstable pod (requests plus a memory limit only) and a besteffort pod (no resources):
$ kubectl -n c-sched get pods -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass
NAME QOS
besteffort BestEffort
burstable Burstable
guaranteed Guaranteed
LimitRange and ResourceQuota
In shared clusters, each namespace needs rules. A LimitRange applies default and maximum values per container; a ResourceQuota caps the namespace total:
apiVersion: v1
kind: LimitRange
metadata:
name: defaults
namespace: c-sched-team
spec:
limits:
- type: Container
defaultRequest: # applied when the container declares no requests
cpu: 100m
memory: 128Mi
default: # applied when the container declares no limits
cpu: 500m
memory: 256Mi
max:
cpu: "1"
memory: 1Gi
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: quota
namespace: c-sched-team
spec:
hard:
requests.cpu: "2"
requests.memory: 2Gi
limits.cpu: "4"
limits.memory: 4Gi
pods: "10"
A pod without resources got the defaults, a pod with a 2-CPU limit was rejected, and a 12-replica Deployment stopped at the quota:
$ kubectl -n c-sched-team get pod no-resources -o jsonpath='{.spec.containers[0].resources}'
{"limits":{"cpu":"500m","memory":"256Mi"},"requests":{"cpu":"100m","memory":"128Mi"}}
Error from server (Forbidden): pods "too-big" is forbidden: maximum cpu usage per Container is 1, but limit is 2
$ kubectl -n c-sched-team get deploy many
NAME READY UP-TO-DATE AVAILABLE AGE
many 7/12 7 7 4s
Warning FailedCreate replicaset-controller Error creating: pods "many-797b98b485-zk29p" is forbidden: exceeded quota: quota, requested: limits.cpu=500m, used: limits.cpu=4, limited: limits.cpu=4
Note that the quota error shows up in the ReplicaSet events, not the Deployment’s. With an active CPU or memory quota, every pod must declare those values, which is why LimitRange and ResourceQuota go together.
Choosing nodes: nodeSelector and node affinity
nodeSelector requires exact labels. Node affinity allows operators (In, NotIn, Exists) and weighted preferences. We used labels every node already has, such as kubernetes.io/hostname and kubernetes.io/os:
apiVersion: v1
kind: Pod
metadata:
name: prefers-worker
namespace: c-sched
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/os
operator: In
values: ["linux"]
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: kubernetes.io/hostname
operator: In
values: ["blog-lab-worker"]
containers:
- name: app
image: registry.k8s.io/pause:3.10
NAME STATUS NODE
pinned-worker2 Running blog-lab-worker2 # nodeSelector kubernetes.io/hostname: blog-lab-worker2
prefers-worker Running blog-lab-worker
In production, prefer topology labels (topology.kubernetes.io/zone) or node pool labels over host names, which change when nodes are replaced.
Spreading replicas
Pod anti-affinity
Required anti-affinity forbids two replicas in the same domain. With three replicas and only two workers, the third has nowhere to go:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels: { app: cache }
topologyKey: kubernetes.io/hostname
Warning FailedScheduling default-scheduler 0/3 nodes are available: 1 node(s) had untolerated taint(s), 2 node(s) didn't match pod anti-affinity rules. preemption: 0/3 nodes are available: 1 Preemption is not helpful for scheduling, 2 No preemption victims found for incoming pod.
Use required when two replicas together are unacceptable; otherwise, preferred avoids stuck pods.
topologySpreadConstraints
topologySpreadConstraints is more flexible: it caps the difference (maxSkew) in replicas between domains. The first version of our test, with four replicas, left two of them Pending with 2 node(s) didn't match pod topology spread constraints. The reason: by default (nodeTaintsPolicy: Ignore), the control plane, which the pod doesn’t tolerate, still counts as a domain with zero replicas, so each worker could only hold one. The second gotcha showed up during the rolling update: pods from the old revision were counted and produced 3 replicas on one node and 1 on the other. The final version fixes both:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: DoNotSchedule
nodeTaintsPolicy: Honor # ignores nodes whose taint the pod doesn't tolerate (the control plane)
matchLabelKeys: ["pod-template-hash"] # counts only pods from the same revision
labelSelector:
matchLabels: { app: api }
$ kubectl -n c-sched rollout restart deploy/api # and, at the end:
api-69f794fc-854ln blog-lab-worker2
api-69f794fc-bk9x9 blog-lab-worker
api-69f794fc-vc9q6 blog-lab-worker2
api-69f794fc-vnqxz blog-lab-worker
Two replicas per worker, even after a rollout. On cloud clusters, combine one constraint on topology.kubernetes.io/zone with another on hostname.
Taints and tolerations
Affinity attracts pods; a taint repels them. A tainted node only accepts pods that tolerate it. The example every cluster has is the control plane’s:
$ kubectl describe node blog-lab-control-plane | grep Taints
Taints: node-role.kubernetes.io/control-plane:NoSchedule
The NoSchedule effect blocks new pods; PreferNoSchedule only avoids them; NoExecute also evicts the ones already there (with optional tolerationSeconds). A toleration doesn’t send the pod to the node; it only allows it. That’s why the test below combines a toleration with a nodeSelector (and we didn’t change the node’s taint):
nodeSelector:
node-role.kubernetes.io/control-plane: ""
tolerations:
- key: node-role.kubernetes.io/control-plane
operator: Exists
effect: NoSchedule
The pod started on blog-lab-control-plane, and we deleted it right away. Taints are the right way to reserve nodes for GPUs or specific teams; Kubernetes also uses automatic taints, such as node.kubernetes.io/not-ready, to move pods off unhealthy nodes.
PriorityClass and preemption
When there’s no room, the scheduler can evict lower-priority pods to fit a higher-priority one:
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: c-critical
value: 100000
preemptionPolicy: PreemptLowerPriority
description: "Checkout and payment APIs"
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: c-batch
value: -10 # below the default (0): first to go
preemptionPolicy: Never # never evicts anyone to get in
description: "Report jobs that can wait"
We pinned a report pod (c-batch, 6 CPUs) to blog-lab-worker2, followed by a checkout pod (c-critical, 6 CPUs). Both didn’t fit:
Warning FailedScheduling pod/checkout 0/3 nodes are available: 1 Insufficient cpu, 1 node(s) didn't match Pod's node affinity/selector, 1 node(s) had untolerated taint(s). preemption: found a potential placement for pod on node blog-lab-worker2, preempting 1 victims
Normal Preempted pod/report Preempted by pod 6dd34020-9ab6-4e5f-9bfb-6f0c936cdeb4 on node blog-lab-worker2
Normal Scheduled pod/checkout Successfully assigned c-sched/checkout to blog-lab-worker2
Since a pod without a priorityClassName has priority 0, the batch class with a negative value ensures that only it becomes a victim. Preemption tries to respect PodDisruptionBudgets, but doesn’t guarantee it. Create few classes, document who may use them, and never use the system-* ones for applications.
Pending pods: reading the events
A Pending pod is almost always explained by kubectl describe pod. We asked for 16 CPUs on 10-CPU nodes:
$ kubectl -n c-sched describe pod greedy
Warning FailedScheduling default-scheduler 0/3 nodes are available: 1 node(s) had untolerated taint(s), 2 Insufficient cpu. preemption: 0/3 nodes are available: 3 Preemption is not helpful for scheduling.
Read the message as arithmetic: 3 nodes, 1 ruled out by a taint, 2 by lack of CPU, and preemption doesn’t help because no node has 16 CPUs. Other common messages are didn't match Pod's node affinity/selector, didn't match pod anti-affinity rules, and unbound immediate PersistentVolumeClaims (see Kubernetes storage). For the full playbook, see troubleshooting and debugging.
In-place pod resize
Since Kubernetes 1.35, in-place resize (InPlacePodVerticalScaling) is GA: you can change a running pod’s CPU and memory through the resize subresource without recreating it. resizePolicy defines whether the change requires restarting the container:
resizePolicy:
- resourceName: cpu
restartPolicy: NotRequired # CPU changes without a restart
- resourceName: memory
restartPolicy: RestartContainer # memory restarts the container
resources:
requests: { cpu: 100m, memory: 64Mi }
limits: { cpu: 200m, memory: 128Mi }
kubectl -n c-sched patch pod resize-demo --subresource resize \
--patch '{"spec":{"containers":[{"name":"app","resources":{"requests":{"cpu":"300m"},"limits":{"cpu":"600m"}}}]}}'
cpu.max before: 20000 100000
status: {"limits":{"cpu":"600m","memory":"128Mi"},"requests":{"cpu":"300m","memory":"64Mi"}}
restarts=0
cpu.max after: 60000 100000
The cgroup went from 200m to 600m without a restart. Raising the memory limit to 256Mi resulted in restarts=1, as the resizePolicy says. A request that doesn’t fit on the node is rejected immediately: node didn't have enough allocatable resources: cpu, requested: 20000, allocatable: 10000. Use resize for one-off adjustments; for continuous tuning, pair it with a vertical autoscaler and check the chosen tool’s support.
Autoscaling: KEDA and Karpenter
Well-defined requests are the foundation of autoscaling. To scale replicas on events (queues, Kafka, cron), use KEDA; for the HPA, see scaling and updating applications. To scale nodes, Karpenter creates right-sized nodes for Pending pods, based on the same requests, affinities, and tolerations covered in this guide.
Checklist
- Every container has CPU and memory requests based on real usage
- LimitRange and ResourceQuota in every shared namespace
- Replicas spread with
topologySpreadConstraints(nodeTaintsPolicyandmatchLabelKeysreviewed) - Taints for special nodes, never changing the control plane’s
- Few, documented PriorityClasses, with batch below zero
-
Pendingpods investigated throughkubectl describeevents - In-place resize tested with the right
resizePolicy
The scheduler doesn’t guess anything: it only reads what you declared. Honest requests, clear labels, and well-thought-out taints do the rest.