Stage 5, Part 1 of 9, Scheduling Deep Dive

Text

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)

DoesDoesn't Do
Watches for unscheduled PodsStart containers
Filters nodes by constraintsManage container lifecycle
Scores feasible nodesHandle networking
Binds Pod to nodeRun health checks
Triggers preemptionPull 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

SourceWhat It Provides
Pod specResource requests, affinity, tolerations, priority
Node statusAvailable resources, taints, labels, conditions
PV/PVC stateStorage availability
TopologyZones, 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

CycleWhat HappensCan Fail?
Scheduling CycleFilter + Score for one PodYes → retry or preempt
Binding CycleWrite nodeName to PodYes → 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:

QueuePurpose
ActiveQueuePods ready to be scheduled
BackoffQueuePods that failed scheduling (retry with backoff)
UnschedulableQueuePods 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

ProsCons
Very simple to writeNo soft preferences
Fast evaluationNo OR logic
Easy to understandPod stays Pending if no match
—No operators like In, NotIn

When to Use Node Selectors

ScenarioNode 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:

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

OperatorMeaning
InLabel value is in the list
NotInLabel value is not in the list
ExistsLabel exists (any value)
DoesNotExistLabel does not exist
GtLabel value > specified (numeric)
LtLabel 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

PatternPurpose
Zone spreadingRequired in specific zones
Hardware targetingGPU, NVMe, FPGA
Environment isolationDev/staging/prod nodes
Cost optimizationSpot vs on-demand
ComplianceData 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":

topologyKeyMeaning
kubernetes.io/hostnamePer node
topology.kubernetes.io/zonePer zone
topology.kubernetes.io/regionPer region
Custom labelCustom 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

OperationCost
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 versionsLower 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

GotchaImpact
Required anti-affinity with replicas > nodesPods stay Pending forever
Required affinity with no matching PodsPod stays Pending forever
Anti-affinity in small clustersCan't schedule multiple replicas
Affinity to selfCircular 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

ConceptWhere SetMeaning
TaintOn the Node"Don't schedule Pods here unless they tolerate this"
TolerationOn the Pod"I can be scheduled on nodes with this taint"

Taint Effects

EffectBehavior
NoScheduleNew Pods without toleration won't schedule here
PreferNoScheduleScheduler tries to avoid, but may schedule
NoExecuteEvicts 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

OperatorBehavior
EqualTaint key AND value must match
ExistsTaint 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

TaintPurpose
node.kubernetes.io/not-readyNode not ready
node.kubernetes.io/unreachableNode unreachable
node.kubernetes.io/memory-pressureMemory pressure
node.kubernetes.io/disk-pressureDisk pressure
node.kubernetes.io/pid-pressurePID pressure
node.kubernetes.io/network-unavailableNetwork unavailable
node.kubernetes.io/unschedulableNode cordoned
node-role.kubernetes.io/control-planeControl 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:

  1. New Pods without toleration → not scheduled
  2. 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?

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

PatternPurpose
Dedicated GPU nodesTaint GPU nodes; only GPU workloads tolerate
Dedicated monitoring nodesTaint monitoring; only monitoring tolerates
Spot node isolationTaint spot nodes; only batch tolerates
Control plane isolationBuilt-in taint on control plane
Node with issuesSystem taints (not-ready, disk-pressure)

1:1 copy of the class Google Doc, code in code blocks.