PART 1: CORE THEORY
1. The Scheduler
The kube-scheduler is a control plane component that watches for newly created Pods with no assigned node, and selects the best node for them.
What the Scheduler Does (and Doesn't Do)
| Does | Doesn't Do |
| Watches for unscheduled Pods | Start containers |
| Filters nodes by constraints | Manage container lifecycle |
| Scores feasible nodes | Handle networking |
| Binds Pod to node | Run health checks |
| Triggers preemption | Pull images |
Critical distinction: The scheduler only writes the node name onto the Pod object. The kubelet on the chosen node does the actual work of starting containers.
What Makes a Pod Unscheduled
A Pod is scheduled when its spec.nodeName field is empty. Once the scheduler assigns it, spec.nodeName is set and the kubelet on that node takes over.
yaml
apiVersion: v1
kind: Pod
metadata:
name: web
spec:
# nodeName: "" (empty → scheduler will assign)
containers:
- name: app
image: nginx
The Scheduler's Sources of Truth
| Source | What It Provides |
| Pod spec | Resource requests, affinity, tolerations, priority |
| Node status | Available resources, taints, labels, conditions |
| PV/PVC state | Storage availability |
| Topology | Zones, regions, hostnames |
The Scheduler's Perspective on Resources
The scheduler operates on requests, not actual usage. A Pod requesting 2 CPUs but using 200m is treated as a 2-CPU Pod during scheduling.
This is why right-sizing requests is critical for cluster efficiency. Over-requesting wastes capacity; under-requesting risks eviction.
2. The Scheduling Pipeline
For every Pending Pod, the scheduler runs a two-phase pipeline, then binds.
The Full Flow
text
┌─────────────────────────────────────────────────────────────┐
│ SCHEDULING PIPELINE │
│ │
│ Pod in Scheduling Queue │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ PHASE 1: FILTERING │ │
│ │ All nodes │ │
│ │ │ │ │
│ │ ├── NodeResourcesFit (enough CPU/mem?) │ │
│ │ ├── NodeAffinity (node labels match?) │ │
│ │ ├── TaintToleration (taints tolerated?) │ │
│ │ ├── PodAffinity (pod co-location?) │ │
│ │ ├── PodAntiAffinity (pod spreading?) │ │
│ │ ├── NodeUnschedulable (cordoned?) │ │
│ │ ├── VolumeBinding (PV available?) │ │
│ │ ├── TopologySpread (zone distribution?) │ │
│ │ └── ... │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ Feasible Nodes │ │
│ └────────────────────┬────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ PHASE 2: SCORING │ │
│ │ Each feasible node gets a score (0-100) │ │
│ │ │ │ │
│ │ ├── NodeResourcesBalancedAllocation │ │
│ │ ├── NodeResourcesFit (LeastAllocated) │ │
│ │ ├── InterPodAffinity │ │
│ │ ├── ImageLocality (image already cached?) │ │
│ │ ├── TaintToleration │ │
│ │ ├── PodTopologySpread │ │
│ │ └── ... │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ Highest-scoring node │ │
│ └────────────────────┬────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ PHASE 3: BINDING │ │
│ │ Write spec.nodeName to Pod via API server │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ If no feasible nodes: │
│ ├── Try preemption (evict lower-priority pods) │
│ └── Or, leave Pod in Pending │
└─────────────────────────────────────────────────────────────┘
The Default Scoring Strategy
The scheduler's default scoring is LeastAllocated — it spreads workloads rather than packing them.
Why? Failure-domain resilience. If all workloads are on one node and that node dies, everything is lost.
Bin packing is opt-in via MostAllocated or RequestedToCapacityRatio.
The Scheduling Cycle vs Binding Cycle
| Cycle | What Happens | Can Fail? |
| Scheduling Cycle | Filter + Score for one Pod | Yes → retry or preempt |
| Binding Cycle | Write nodeName to Pod | Yes → retry |
The scheduling cycle is synchronous per Pod, but multiple Pods can be in different cycles concurrently.
The Scheduling Queue
Pods enter one of three queues:
| Queue | Purpose |
| ActiveQueue | Pods ready to be scheduled |
| BackoffQueue | Pods that failed scheduling (retry with backoff) |
| UnschedulableQueue | Pods that can't be scheduled (waiting for events) |
When cluster state changes (node added, Pod deleted, etc.), Pods move from Unschedulable to Active.
3. Node Selectors
Node Selectors are the simplest way to constrain Pod scheduling to specific nodes. They are hard, all-or-nothing requirements.
How Node Selectors Work
yaml
apiVersion: v1
kind: Pod
metadata:
name: gpu-pod
spec:
nodeSelector:
gpu: "true" # Pod must run on a node labeled gpu=true
accelerator: nvidia-a100
containers:
- name: ml-app
image: ml-app:1.0
Labeling Nodes
bash
# Add a label
kubectl label nodes node-1 gpu=true
kubectl label nodes node-2 accelerator=nvidia-a100
# View labels
kubectl get nodes --show-labels
kubectl describe node node-1 | grep -A5 Labels
# Remove a label
kubectl label nodes node-1 gpu-
Pros and Cons
| Pros | Cons |
| Very simple to write | No soft preferences |
| Fast evaluation | No OR logic |
| Easy to understand | Pod stays Pending if no match |
| — | No operators like In, NotIn |
When to Use Node Selectors
| Scenario | Node Selector OK? |
Simple env separation (env: prod) | ✅ Yes |
Simple hardware type (disktype: ssd) | ✅ Yes |
| Complex multi-condition | ❌ Use Node Affinity |
| Prefer but don't require | ❌ Use Node Affinity |
| Pod co-location | ❌ Use Pod Affinity |
The Node Selector Trap
If you set nodeSelector: {gpu: "true"} and no node has that label, the Pod stays Pending forever with no clear indication why. Always use kubectl describe pod to see Events.
4. Node Affinity and Anti-Affinity
Node Affinity is the advanced version of Node Selectors. It supports:
- Hard requirements (
requiredDuringSchedulingIgnoredDuringExecution) - Soft preferences (
preferredDuringSchedulingIgnoredDuringExecution) - Rich operators (
In,NotIn,Exists,DoesNotExist,Gt,Lt)
Required Node Affinity
yaml
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: topology.kubernetes.io/zone
operator: In
values:
- us-east-1a
- us-east-1b
- key: node-type
operator: In
values:
- gpu
Behavior: Pod stays Pending if no node matches.
Preferred Node Affinity
yaml
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: node-type
operator: In
values:
- gpu
- weight: 50
preference:
matchExpressions:
- key: disktype
operator: In
values:
- ssd
Behavior: Scheduler tries to honor preferences, but schedules elsewhere if needed. Weights range 1-100.
The Operators
| Operator | Meaning |
In | Label value is in the list |
NotIn | Label value is not in the list |
Exists | Label exists (any value) |
DoesNotExist | Label does not exist |
Gt | Label value > specified (numeric) |
Lt | Label value < specified (numeric) |
Multiple nodeSelectorTerms = OR
yaml
nodeSelectorTerms:
- matchExpressions:
- key: zone
operator: In
values: [us-east-1a] # OR
- matchExpressions:
- key: zone
operator: In
values: [us-east-1b] # OR
Multiple matchExpressions = AND
yaml
nodeSelectorTerms:
- matchExpressions:
- key: zone
operator: In
values: [us-east-1a] # AND
- key: gpu
operator: In
values: ["true"] # AND
Combining Required and Preferred
yaml
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: topology.kubernetes.io/region
operator: In
values: [us-east-1] # MUST be in region
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: topology.kubernetes.io/zone
operator: In
values: [us-east-1a] # PREFER this zone
The "IgnoredDuringExecution" Meaning
requiredDuringScheduling = enforced at scheduling time.
IgnoredDuringExecution = if node labels change after the Pod is scheduled, the Pod keeps running.
So: Existing Pods aren't evicted if node labels change.
Common Node Affinity Patterns
| Pattern | Purpose |
| Zone spreading | Required in specific zones |
| Hardware targeting | GPU, NVMe, FPGA |
| Environment isolation | Dev/staging/prod nodes |
| Cost optimization | Spot vs on-demand |
| Compliance | Data residency (EU-only nodes) |
5. Pod Affinity and Anti-Affinity
Pod Affinity and Pod Anti-Affinity control Pod placement relative to other Pods, based on their labels.
Pod Affinity (Co-location)
Bring Pods together on the same node/zone.
yaml
spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: cache
topologyKey: kubernetes.io/hostname
Behavior: This Pod must be scheduled on a node that already has a Pod labeled app=cache.
Use case: Web server needs to be close to its cache (low latency).
Pod Anti-Affinity (Spreading)
Keep Pods apart.
yaml
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: web
topologyKey: kubernetes.io/hostname
Behavior: This Pod must NOT be scheduled on a node that already has a Pod labeled app=web.
Use case: Ensure web replicas are on different nodes (HA).
The topologyKey
The topologyKey is the node label that defines the "failure domain":
| topologyKey | Meaning |
kubernetes.io/hostname | Per node |
topology.kubernetes.io/zone | Per zone |
topology.kubernetes.io/region | Per region |
| Custom label | Custom domain |
Example: topologyKey: topology.kubernetes.io/zone for pod anti-affinity spreads replicas across zones.
Soft vs Hard
yaml
# HARD: Pod stays Pending if no node satisfies
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector: {...}
topologyKey: kubernetes.io/hostname
# SOFT: Try to satisfy, but schedule anyway
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector: {...}
topologyKey: kubernetes.io/hostname
The HA Pattern (Multi-AZ)
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: web
topologyKey: topology.kubernetes.io/zone # One per zone
containers:
- name: web
image: nginx
Result: 3 replicas spread across 3 zones.
The Low-Latency Pattern (Co-location)
yaml
spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: cache
topologyKey: kubernetes.io/hostname # Same node as cache
Result: Always on the same node as the cache. Reduces network latency.
The Cost of Pod Affinity/Anti-Affinity
| Operation | Cost |
| Pod Affinity (required) | High — scheduler must scan all Pods on each candidate node |
| Pod Anti-Affinity (required) | High — scheduler must ensure no matching Pod exists |
| Preferred versions | Lower cost but less strong guarantee |
Performance tip: For large clusters, prefer topologyKey: topology.kubernetes.io/zone over hostname, as it requires fewer nodes to check.
Pod Affinity/Anti-Affinity Gotchas
| Gotcha | Impact |
| Required anti-affinity with replicas > nodes | Pods stay Pending forever |
| Required affinity with no matching Pods | Pod stays Pending forever |
| Anti-affinity in small clusters | Can't schedule multiple replicas |
| Affinity to self | Circular dependency |
Production rule: Use required only when you're certain it can always be satisfied. Prefer preferred for flexibility.
6. Taints and Tolerations
Taints let a node repel Pods. Tolerations let a Pod be scheduled on a tainted node.
The Gatekeeper Model
| Concept | Where Set | Meaning |
| Taint | On the Node | "Don't schedule Pods here unless they tolerate this" |
| Toleration | On the Pod | "I can be scheduled on nodes with this taint" |
Taint Effects
| Effect | Behavior |
| NoSchedule | New Pods without toleration won't schedule here |
| PreferNoSchedule | Scheduler tries to avoid, but may schedule |
| NoExecute | Evicts existing Pods without toleration; new Pods won't schedule |
Adding Taints
bash
# Add a taint
kubectl taint nodes node-1 dedicated=gpu:NoSchedule
# Add with PreferNoSchedule
kubectl taint nodes node-2 workload=monitoring:PreferNoSchedule
# View taints
kubectl describe node node-1 | grep Taints
# Remove a taint
kubectl taint nodes node-1 dedicated-
Toleration Structure
yaml
spec:
tolerations:
- key: "dedicated"
operator: "Equal"
value: "gpu"
effect: "NoSchedule"
Toleration Operators
| Operator | Behavior |
| Equal | Taint key AND value must match |
| Exists | Taint key must match (any value) |
Toleration Examples
Tolerate a specific taint:
yaml
tolerations:
- key: "dedicated"
operator: "Equal"
value: "gpu"
effect: "NoSchedule"
Tolerate any taint on a key:
yaml
tolerations:
- key: "dedicated"
operator: "Exists"
effect: "NoSchedule"
Tolerate all taints (for DaemonSets):
yaml
tolerations:
- operator: "Exists"
Tolerate a taint for a limited time (NoExecute):
yaml
tolerations:
- key: "node.kubernetes.io/unreachable"
operator: "Exists"
effect: "NoExecute"
tolerationSeconds: 300
Built-in Taints
| Taint | Purpose |
node.kubernetes.io/not-ready | Node not ready |
node.kubernetes.io/unreachable | Node unreachable |
node.kubernetes.io/memory-pressure | Memory pressure |
node.kubernetes.io/disk-pressure | Disk pressure |
node.kubernetes.io/pid-pressure | PID pressure |
node.kubernetes.io/network-unavailable | Network unavailable |
node.kubernetes.io/unschedulable | Node cordoned |
node-role.kubernetes.io/control-plane | Control plane node |
The Control Plane Taint
Control plane nodes are tainted:
text
node-role.kubernetes.io/control-plane:NoSchedule
To schedule a Pod on control plane nodes:
yaml
tolerations:
- key: "node-role.kubernetes.io/control-plane"
operator: "Exists"
effect: "NoSchedule"
Warning: Running workloads on control plane nodes is risky. Only do it for cluster-critical services.
The NoExecute Effect
NoExecute is the most aggressive:
- New Pods without toleration → not scheduled
- Existing Pods without toleration → evicted
When a node becomes unreachable, the node.kubernetes.io/unreachable taint is added with NoExecute. The default toleration (auto-added to all Pods) is 300 seconds:
yaml
tolerations:
- key: "node.kubernetes.io/not-ready"
operator: "Exists"
effect: "NoExecute"
tolerationSeconds: 300
- key: "node.kubernetes.io/unreachable"
operator: "Exists"
effect: "NoExecute"
tolerationSeconds: 300
After 300 seconds (5 minutes), Pods are evicted from the unreachable node.
The Dedicated Node Pattern
Use case: Reserve nodes for specific workloads.
bash
# Taint the node
kubectl taint nodes gpu-node-1 dedicated=gpu:NoSchedule
yaml
# GPU workload tolerates the taint + uses node affinity
spec:
tolerations:
- key: "dedicated"
operator: "Equal"
value: "gpu"
effect: "NoSchedule"
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: dedicated
operator: In
values: [gpu]
Why both taint AND affinity?
- The taint keeps other Pods off the GPU node.
- The affinity keeps the GPU Pod on the GPU node.
Without affinity, a GPU Pod could be scheduled on a non-GPU node (if it tolerates the GPU taint and another node has no taint).
Common Taint/Toleration Patterns
| Pattern | Purpose |
| Dedicated GPU nodes | Taint GPU nodes; only GPU workloads tolerate |
| Dedicated monitoring nodes | Taint monitoring; only monitoring tolerates |
| Spot node isolation | Taint spot nodes; only batch tolerates |
| Control plane isolation | Built-in taint on control plane |
| Node with issues | System taints (not-ready, disk-pressure) |
1:1 copy of the class Google Doc, code in code blocks.