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
| Class | Value | Purpose |
system-node-critical | 2000001000 | Node-level components (kube-proxy, CNI) |
system-cluster-critical | 2000000000 | Cluster-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
- Queue order: Higher-priority Pods are scheduled first.
- Preemption: If a high-priority Pod can't schedule, lower-priority Pods may be preempted.
Preemption
When a high-priority Pod is Pending:
- Scheduler looks for nodes where the Pod would fit if some lower-priority Pods were removed.
- Picks the node that minimizes disruption.
- Marks lower-priority Pods for eviction.
- 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-Pattern | Impact |
| All Pods same priority | No preemption benefit |
| Everything high priority | Defeats the purpose; races |
| Priority without PDBs | Preemption kills critical Pods |
| Ignoring system priorities | User Pods can preempt control plane Pods (rare) |
Priority Classes Design
| Priority | Use Case |
| 2000001000 | system-node-critical (reserved) |
| 2000000000 | system-cluster-critical (reserved) |
| 1000000 | Production user-facing APIs |
| 100000 | Production backend services |
| 10000 | Batch jobs, pipelines |
| 1000 | Development workloads |
| 0 | Default (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:
| Parameter | Meaning |
maxSkew | Maximum difference in Pod count between domains |
topologyKey | Node label defining the domain |
whenUnsatisfiable | DoNotSchedule or ScheduleAnyway |
labelSelector | Which Pods to count |
minDomains | Minimum 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
| Value | Behavior |
DoNotSchedule | Hard requirement — Pod stays Pending if constraint can't be met |
ScheduleAnyway | Soft 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
| Aspect | Topology Spread | Anti-Affinity |
| Declarative | ✅ Yes | ⚠️ Less so |
| Balance | ✅ Even distribution | ❌ Only "not together" |
| Complexity | Simple maxSkew | Complex selectors |
| Performance | Better | Can be slow |
| Best for | HA, balanced spread | Strict 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
| Scenario | Use 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
| Scenario | Use 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 Point | Purpose |
| QueueSort | Sort Pods in the scheduling queue |
| PreFilter | Pre-process Pod info; check if feasible nodes exist |
| Filter | Eliminate infeasible nodes |
| PostFilter | Handle unschedulable Pods (preemption) |
| PreScore | Pre-process scoring |
| Score | Score each feasible node (0-100) |
| NormalizeScore | Normalize scores across plugins |
| Reserve | Reserve resources on the chosen node |
| Permit | Allow/deny/wait before binding |
| PreBind | Pre-binding setup |
| Bind | Finalize 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
| Plugin | Extension Points |
| NodeResourcesFit | Filter, Score |
| NodeAffinity | Filter, Score |
| PodTopologySpread | PreFilter, Filter, PreScore, Score |
| InterPodAffinity | PreFilter, Filter, PreScore, Score |
| TaintToleration | Filter, Score |
| ImageLocality | Score |
| DefaultPreemption | PostFilter |
| VolumeBinding | PreFilter, Filter, Reserve, PreBind |
Custom Plugins
You can write your own plugins in Go and register them. Common use cases:
| Use Case | Plugin Type |
| Custom scoring | Score |
| Hardware-aware placement | Filter, Score |
| Custom preemption | PostFilter |
| Multi-tenant fairness | QueueSort, 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 Case | Custom Scheduler |
| Batch jobs | Gang scheduling, queue-based |
| ML training | GPU-aware, gang, topology |
| HPC | NUMA-aware, network topology |
| Specialized hardware | FPGA, TPU |
| Custom policies | Business rules |
Deploying a Custom Scheduler
- Build a binary using the Scheduler Framework.
- Deploy it as a Deployment or static Pod.
- Register it with the API server (via ServiceAccount, RBAC).
- 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
| Scheduler | Purpose |
| Volcano | Batch AI/ML, gang scheduling |
| Kueue | Job queueing and quotas |
| YuniKorn | Big data, batch |
| Scheduler Plugins | ML, 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:
- Node additions/removals
- Pod evictions
- Priority changes
- Workload changes
The Descheduler continuously looks for Pods that violate scheduling policies and evicts them, letting the scheduler re-place them.
Common Descheduler Strategies
| Strategy | Purpose |
| RemoveDuplicates | No two replicas on the same node |
| LowNodeUtilization | Balance resource usage across nodes |
| HighNodeUtilization | Pack workloads (for scale-to-zero) |
| RemovePodsViolatingInterPodAntiAffinity | Enforce anti-affinity |
| RemovePodsViolatingNodeAffinity | Enforce node affinity |
| RemovePodsViolatingNodeTaints | Enforce taints |
| RemovePodsViolatingTopologySpreadConstraint | Enforce spread |
| RemovePodsHavingTooManyRestarts | Evict crashlooping Pods |
| PodLifeTime | Evict 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
| Component | Purpose |
| Topology Manager | Kubelet-level NUMA alignment |
| CPU Manager | Static CPU allocation |
Enabling Topology Manager
In /var/lib/kubelet/config.yaml:
yaml
topologyManagerPolicy: single-numa-node
cpuManagerPolicy: static
Restart kubelet.
The Topology Policies
| Policy | Behavior |
| none | No alignment |
| best-effort | Try to align; don't fail |
| restricted | Align if possible; fail if not |
| single-numa-node | All 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:
- QoS must be Guaranteed (requests == limits)
- CPU requests must be integers
When to Use NUMA-Aware Scheduling
| Workload | NUMA-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:
- NVIDIA Device Plugin exposes GPUs to Kubernetes.
- GPUs are not compressible — one Pod gets one GPU unless MIG/time-slicing is used.
- Node affinity targets GPU nodes.
- Taints keep non-GPU workloads off GPU nodes.
- Dynamic Resource Allocation (DRA) is the future (K8s 1.26+).
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:
- Volcano — gang scheduling plugin
- Kueue — job queueing
- YuniKorn — gang scheduling
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.