Stage 5, Part 2 of 9, Scheduling Deep Dive

Text

PART 2: ADVANCED CONCEPTS

7. Priority Classes and Preemption

PriorityClass

A PriorityClass is a cluster-scoped object that assigns an integer priority to a Pod. Higher numbers = higher priority.

yaml
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
  name: high-priority
value: 1000000
globalDefault: false
description: "For production critical services"

Built-in System PriorityClasses

ClassValuePurpose
system-node-critical2000001000Node-level components (kube-proxy, CNI)
system-cluster-critical2000000000Cluster-level components (DNS, metrics-server)

These have reserved values to prevent user-defined priorities from exceeding them.

Using PriorityClass

yaml
apiVersion: v1
kind: Pod
metadata:
  name: critical-api
spec:
  priorityClassName: high-priority
  containers:
  - name: api
    image: myapi:1.0

How Priority Affects Scheduling

  1. Queue order: Higher-priority Pods are scheduled first.
  2. Preemption: If a high-priority Pod can't schedule, lower-priority Pods may be preempted.

Preemption

When a high-priority Pod is Pending:

  1. Scheduler looks for nodes where the Pod would fit if some lower-priority Pods were removed.
  2. Picks the node that minimizes disruption.
  3. Marks lower-priority Pods for eviction.
  4. Binds the high-priority Pod to the node.

Key insight: Preemption is disruptive. Only use it when you genuinely need priority differentiation.

Preemption and PDBs

PDBs are respected during preemption. If evicting a Pod would violate its PDB, preemption is skipped for that Pod.

Preemption Anti-Patterns

Anti-PatternImpact
All Pods same priorityNo preemption benefit
Everything high priorityDefeats the purpose; races
Priority without PDBsPreemption kills critical Pods
Ignoring system prioritiesUser Pods can preempt control plane Pods (rare)

Priority Classes Design

PriorityUse Case
2000001000system-node-critical (reserved)
2000000000system-cluster-critical (reserved)
1000000Production user-facing APIs
100000Production backend services
10000Batch jobs, pipelines
1000Development workloads
0Default (no priority)

8. Topology Spread Constraints

Topology Spread Constraints control how Pods are distributed across failure domains (zones, nodes, regions).

Why Topology Spread

Before Topology Spread Constraints, distributing Pods across zones required complex Pod anti-affinity. Topology Spread is more declarative and flexible.

Basic Topology Spread

yaml
spec:
  topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: DoNotSchedule
    labelSelector:
      matchLabels:
        app: web

Parameters:

ParameterMeaning
maxSkewMaximum difference in Pod count between domains
topologyKeyNode label defining the domain
whenUnsatisfiableDoNotSchedule or ScheduleAnyway
labelSelectorWhich Pods to count
minDomainsMinimum number of domains required (K8s 1.28+)

The maxSkew Concept

text
Zone A: 2 Pods
Zone B: 1 Pod
Zone C: 2 Pods

maxSkew = 1 → OK
maxSkew = 0 → Would require zones to be exactly equal

maxSkew: 1 is the standard for HA.

whenUnsatisfiable

ValueBehavior
DoNotScheduleHard requirement — Pod stays Pending if constraint can't be met
ScheduleAnywaySoft preference — try to satisfy, but schedule anyway

Multi-Zone HA Example

yaml
spec:
  replicas: 6
  template:
    spec:
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: DoNotSchedule
        labelSelector:
          matchLabels:
            app: web
      - maxSkew: 1
        topologyKey: kubernetes.io/hostname
        whenUnsatisfiable: ScheduleAnyway
        labelSelector:
          matchLabels:
            app: web

Result: 6 replicas evenly spread across zones (hard), and preferred to spread across nodes within a zone (soft).

Combining Node Affinity + Topology Spread

yaml
spec:
  topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: DoNotSchedule
    labelSelector:
      matchLabels:
        app: web
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: topology.kubernetes.io/region
            operator: In
            values: [us-east-1]

Result: Pods spread evenly across zones within us-east-1.

The minDomains Parameter (K8s 1.28+)

yaml
topologySpreadConstraints:
- maxSkew: 1
  minDomains: 3
  topologyKey: topology.kubernetes.io/zone
  whenUnsatisfiable: DoNotSchedule
  labelSelector:
    matchLabels:
      app: web

Behavior: If fewer than minDomains domains are available, the Pod stays Pending. This prevents scheduling in degraded clusters with fewer zones.

Topology Spread vs Anti-Affinity

AspectTopology SpreadAnti-Affinity
Declarative✅ Yes⚠️ Less so
Balance✅ Even distribution❌ Only "not together"
ComplexitySimple maxSkewComplex selectors
PerformanceBetterCan be slow
Best forHA, balanced spreadStrict co-location/separation

Recommendation: Use Topology Spread for HA. Use Pod Anti-Affinity only when you need strict "never together" semantics.


9. Pod Topology Spread vs Anti-Affinity

This is a common question. Here's the breakdown.

When to Use Pod Anti-Affinity

ScenarioUse Anti-Affinity?
Strict 1-per-node✅ Required anti-affinity
Never co-locate two specific apps✅ Required anti-affinity
Balance across zones❌ Use Topology Spread
Soft preference to spread❌ Use Topology Spread (ScheduleAnyway)

When to Use Topology Spread

ScenarioUse Topology Spread?
Even distribution across zones✅ Yes
Even distribution across nodes✅ Yes
Tolerate some skew✅ Yes (maxSkew)
Strict "never together"❌ Use Anti-Affinity

The "Best of Both" Pattern

yaml
topologySpreadConstraints:
- maxSkew: 1
  topologyKey: kubernetes.io/hostname
  whenUnsatisfiable: DoNotSchedule
  labelSelector:
    matchLabels:
      app: web

This is functionally equivalent to required pod anti-affinity with topologyKey: kubernetes.io/hostname, but with better performance and clearer semantics.


10. The Scheduler Framework

The Scheduler Framework is the plugin architecture that powers the scheduler. It has ten extension points where plugins can hook in.

The Extension Points

Extension PointPurpose
QueueSortSort Pods in the scheduling queue
PreFilterPre-process Pod info; check if feasible nodes exist
FilterEliminate infeasible nodes
PostFilterHandle unschedulable Pods (preemption)
PreScorePre-process scoring
ScoreScore each feasible node (0-100)
NormalizeScoreNormalize scores across plugins
ReserveReserve resources on the chosen node
PermitAllow/deny/wait before binding
PreBindPre-binding setup
BindFinalize the binding

The Plugin Cycle

text
For each Pod:
  QueueSort → PreFilter → Filter
    │
    ├── Feasible nodes exist → Continue
    │
    └── No feasible nodes → PostFilter (preemption)
    │
  PreScore → Score → NormalizeScore
    │
  Reserve → Permit → PreBind → Bind

Built-in Plugins

PluginExtension Points
NodeResourcesFitFilter, Score
NodeAffinityFilter, Score
PodTopologySpreadPreFilter, Filter, PreScore, Score
InterPodAffinityPreFilter, Filter, PreScore, Score
TaintTolerationFilter, Score
ImageLocalityScore
DefaultPreemptionPostFilter
VolumeBindingPreFilter, Filter, Reserve, PreBind

Custom Plugins

You can write your own plugins in Go and register them. Common use cases:

Use CasePlugin Type
Custom scoringScore
Hardware-aware placementFilter, Score
Custom preemptionPostFilter
Multi-tenant fairnessQueueSort, Score

The KubeSchedulerConfiguration

The scheduler is configured via a YAML file:

yaml
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: default-scheduler
  plugins:
    score:
      enabled:
      - name: MyCustomScorer
        weight: 5
      disabled:
      - name: NodeResourcesBalancedAllocation

This config is passed to kube-scheduler via --config=/path/to/config.yaml.


11. Custom Schedulers

You can run multiple schedulers in the same cluster. Each Pod specifies which scheduler to use.

Why Multiple Schedulers

Use CaseCustom Scheduler
Batch jobsGang scheduling, queue-based
ML trainingGPU-aware, gang, topology
HPCNUMA-aware, network topology
Specialized hardwareFPGA, TPU
Custom policiesBusiness rules

Deploying a Custom Scheduler

  1. Build a binary using the Scheduler Framework.
  2. Deploy it as a Deployment or static Pod.
  3. Register it with the API server (via ServiceAccount, RBAC).
  4. Pods specify schedulerName: my-scheduler.

Using a Custom Scheduler

yaml
apiVersion: v1
kind: Pod
metadata:
  name: batch-job
spec:
  schedulerName: my-batch-scheduler
  containers:
  - name: worker
    image: batch-worker:1.0

Pods without schedulerName use default-scheduler.

Real-World Custom Schedulers

SchedulerPurpose
VolcanoBatch AI/ML, gang scheduling
KueueJob queueing and quotas
YuniKornBig data, batch
Scheduler PluginsML, GPU-aware

We'll cover these in detail in Stage 13 (AI/ML Workload Orchestration).


12. Scheduler Profiles

Multiple schedulers can be deployed as profiles within a single binary. Each profile has its own plugin configuration.

Configuring Multiple Profiles

yaml
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: default-scheduler
  plugins:
    score:
      disabled:
      - name: NodeResourcesBalancedAllocation

- schedulerName: batch-scheduler
  plugins:
    score:
      enabled:
      - name: NodeResourcesFit
        weight: 10
      disabled:
      - name: NodeResourcesBalancedAllocation
      - name: ImageLocality

Using a Profile

Pods reference the profile by name:

yaml
spec:
  schedulerName: batch-scheduler

This is more efficient than running separate scheduler binaries.


13. The Descheduler

The Descheduler is a tool that evicts Pods to rebalance the cluster, applying the scheduler's rules to existing Pods.

Why the Descheduler

The scheduler makes decisions at Pod creation time. Over time, the cluster can become unbalanced due to:

The Descheduler continuously looks for Pods that violate scheduling policies and evicts them, letting the scheduler re-place them.

Common Descheduler Strategies

StrategyPurpose
RemoveDuplicatesNo two replicas on the same node
LowNodeUtilizationBalance resource usage across nodes
HighNodeUtilizationPack workloads (for scale-to-zero)
RemovePodsViolatingInterPodAntiAffinityEnforce anti-affinity
RemovePodsViolatingNodeAffinityEnforce node affinity
RemovePodsViolatingNodeTaintsEnforce taints
RemovePodsViolatingTopologySpreadConstraintEnforce spread
RemovePodsHavingTooManyRestartsEvict crashlooping Pods
PodLifeTimeEvict Pods older than N

Deploying the Descheduler

yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: descheduler-policy
  namespace: kube-system
data:
  policy.yaml: |
    apiVersion: descheduler/v1alpha1
    kind: DeschedulerPolicy
    strategies:
      RemoveDuplicates:
        enabled: true
      LowNodeUtilization:
        enabled: true
        params:
          thresholds:
            cpu: 20
            memory: 20
            pods: 20
          targetThresholds:
            cpu: 50
            memory: 50
            pods: 50
      RemovePodsViolatingTopologySpreadConstraint:
        enabled: true

Run as a CronJob or Deployment:

yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: descheduler
  namespace: kube-system
spec:
  schedule: "*/15 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: descheduler-sa
          containers:
          - name: descheduler
            image: registry.k8s.io/descheduler/descheduler:latest
            args:
            - --policy-config-file=/policy/policy.yaml
            - --v=3
            volumeMounts:
            - name: policy
              mountPath: /policy
          volumes:
          - name: policy
            configMap:
              name: descheduler-policy

The Descheduler Dry Run

Always start in dry-run mode:

bash
--dry-run

Then transition to actual evictions.

The PDB Interaction

The Descheduler respects PDBs. Pods protected by PDBs are not evicted if it would violate the budget.


14. NUMA-Aware Scheduling

NUMA (Non-Uniform Memory Access) is a memory architecture where CPUs access local memory faster than remote memory. For latency-sensitive workloads, NUMA placement matters.

The NUMA Topology

text
NUMA Node 0                     NUMA Node 1
┌─────────────────────┐         ┌─────────────────────┐
│  CPU 0-7            │         │  CPU 8-15           │
│  Memory: 32 GB      │         │  Memory: 32 GB      │
└──────────┬──────────┘         └──────────┬──────────┘
           │                                │
           └────────────┬───────────────────┘
                        │
                   Interconnect

NUMA-Aware Scheduling Requires Two Components

ComponentPurpose
Topology ManagerKubelet-level NUMA alignment
CPU ManagerStatic CPU allocation

Enabling Topology Manager

In /var/lib/kubelet/config.yaml:

yaml
topologyManagerPolicy: single-numa-node
cpuManagerPolicy: static

Restart kubelet.

The Topology Policies

PolicyBehavior
noneNo alignment
best-effortTry to align; don't fail
restrictedAlign if possible; fail if not
single-numa-nodeAll resources on one NUMA node

Pod Configuration for NUMA-Awareness

yaml
spec:
  containers:
  - name: latency-sensitive
    resources:
      requests:
        cpu: "4"
        memory: "8Gi"
      limits:
        cpu: "4"
        memory: "8Gi"     # Guaranteed QoS required

Requirements:

When to Use NUMA-Aware Scheduling

WorkloadNUMA-Aware?
Low-latency trading✅ Yes
5G/telecom✅ Yes
High-perf databases✅ Yes
General web apps❌ No
Batch jobs❌ No

15. GPU Scheduling (Preview)

GPU scheduling is covered in depth in Stage 12. Key facts:


16. Gang Scheduling (Preview)

Gang scheduling requires all Pods in a group to be scheduled together, or none.

Why it matters for AI/ML: Distributed training jobs need all workers running simultaneously. If only some workers are scheduled, the job deadlocks.

Tools:

Covered in depth in Stage 13.


17. Scheduling Gates and Delays

Scheduling Gates (K8s 1.27+)

Scheduling gates let external controllers hold Pods out of scheduling until ready.

yaml
spec:
  schedulingGates:
  - name: "my-controller/ready"

The Pod stays Pending until a controller removes the gate.

Use case: Complex initialization sequences, multi-controller coordination.

Scheduler Delay Hints

The scheduler caches node information. For very large clusters, this cache can become stale. Delay hints help with accuracy.

PodSchedulingReadiness Gate

A feature gate in K8s 1.26+ that enables scheduling gates for Pods.


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