Advanced Pod Scheduling: Affinity, Taints, Tolerations, Topology

Fine-tune pod placement across your Kubernetes cluster using node affinity, pod affinity/anti-affinity, taints/tolerations, and topology spread constraints.

published: reading time: 31 min read author: Geek Workbench updated: November 21, 2026
Quick Summary

Kubernetes v1.37.1 schedules Pods using resource requests, node state, and placement rules. Taints repel Pods that lack a matching toleration, while affinity and topology spread constraints can require or prefer particular placement. Priority and preemption affect scheduling order, but PodDisruptionBudgets do not guarantee placement or capacity.

Advanced Pod Scheduling: Taints, Tolerations, Affinity, and Topology

This guide uses Kubernetes v1.37.1, the latest patch in the v1.37 release series as of November 21, 2026. The examples use the stable scheduler APIs available in that release.

Kubernetes schedules Pods onto nodes using resource requests, node state, and placement rules. You can add constraints when workloads need specific hardware, must run near or apart from other Pods, or should be spread across availability zones. Kubernetes provides taints and tolerations, affinity rules, and topology spread constraints for these decisions.

This post explains the default scheduling process and the placement controls available for specialized workloads.

For Kubernetes basics, see the Kubernetes fundamentals post. For high availability patterns, see the High Availability post.

Introduction

Use scheduling mechanisms when

  • Specialized hardware is involved. GPU nodes, high-memory machines, nodes with local SSDs all warrant explicit placement decisions.
  • Multiple teams share a cluster and need separate workload placement. Taints and affinity can help keep workloads on different node pools; they are not a security boundary.
  • Availability requirements call for zone distribution. Spreading Pods can reduce the impact of a zone outage, provided enough eligible capacity remains.
  • Related Pods should co-locate or spread apart. A cache and its backend may benefit from being near each other, while replicas may need separation.

Skip custom scheduling when

  • Default scheduling works. The scheduler is good at what it does. Do not add constraints unless you have a problem default scheduling does not solve.
  • Your cluster is small. If you have three nodes and no specialized hardware, affinity rules may add maintenance without solving a placement problem.
  • You are adding constraints “just in case.” Over-constrained clusters leave pods pending.

Scheduling Decision Flow

flowchart TD
    A[Pod created<br/>no node assigned] --> B[Filter: Which nodes<br/>can run this pod?]
    B --> C{Enough nodes<br/>pass filtering?}
    C -->|No| D[Pod stays Pending]
    C -->|Yes| E[Score: Rank nodes<br/>by scheduling criteria]
    E --> F[Select highest<br/>score node]
    F --> G[Bind pod to node<br/>Pod starts]

The scheduler filters out nodes that cannot run a Pod because of resource requests, taints, selectors, or other constraints. It then scores the remaining nodes and chooses one.

How Default Scheduling Works

The Kubernetes scheduler runs as a control-plane component. When a Pod has no node assignment, the scheduler evaluates eligible nodes and selects one.

The scheduling process has two phases:

  1. Filtering: Find nodes that can run the Pod, based on resource availability, node selectors, taints, and other requirements.
  2. Scoring: Rank the remaining nodes using preferences such as affinity, resource utilization, and topology.

The scheduler uses plugins for each phase. Filtering plugins remove nodes that cannot run the Pod; scoring plugins rank the remaining nodes.

You can configure multiple schedulers and assign pods to specific schedulers:

spec:
  schedulerName: custom-scheduler

Without this field, pods use the default scheduler.

Taints and Tolerations for Node Exclusion

Node taints repel Pods that do not tolerate them. A Pod toleration allows the Pod to be considered for a node with a matching taint; it does not attract the Pod to that node or guarantee placement there. Use a node selector or node affinity as well when a Pod must target a labeled node pool.

Adding a taint to a node

kubectl taint nodes node1 dedicated=postgres:NoSchedule

This taint has a key (dedicated), value (postgres), and effect (NoSchedule). The effect determines how the scheduler treats Pods without a matching toleration:

Effect Behavior
NoSchedule New Pods without a matching toleration are not scheduled on the node
PreferNoSchedule Scheduler avoids the node when possible, but may use it
NoExecute Existing Pods without a matching toleration are evicted; new Pods are not scheduled there

Tolerations in a pod spec

spec:
  tolerations:
    - key: "dedicated"
      operator: "Equal"
      value: "postgres"
      effect: "NoSchedule"

This toleration matches the dedicated=postgres:NoSchedule taint, so the scheduler may place the Pod on that node if it also satisfies the Pod’s other requirements. The toleration does not select the node or reserve its capacity.

Using Equal vs Exists operator

# Equal: match specific value
tolerations:
  - key: "dedicated"
    operator: "Equal"
    value: "postgres"
    effect: "NoSchedule"

# Exists: match key regardless of value
tolerations:
  - key: "dedicated"
    operator: "Exists"
    effect: "NoSchedule"

The Exists operator matches any value for the key. Neither operator selects a node; a toleration only removes the matching taint as a scheduling barrier.

Common taint use cases

Mark nodes for specific workloads:

kubectl taint nodes node-gpu gpu-workload:NoSchedule
kubectl taint nodes node-batch batch-job:NoExecute
kubectl taint nodes node1 infra=proxy:PreferNoSchedule

Pods that may use GPU nodes add a matching toleration. To keep them on GPU nodes, also select a GPU node label with node affinity or nodeSelector:

tolerations:
  - key: "gpu-workload"
    operator: "Exists"
    effect: "NoSchedule"

Node Affinity Rules

Node affinity matches node labels and supports both hard requirements (requiredDuringSchedulingIgnoredDuringExecution) and soft preferences (preferredDuringSchedulingIgnoredDuringExecution). It offers more expression options than nodeSelector.

Required node affinity

spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
          - matchExpressions:
              - key: "topology.kubernetes.io/zone"
                operator: In
                values:
                  - us-east-1a
                  - us-east-1b
              - key: "node.kubernetes.io/disktype"
                operator: In
                values:
                  - ssd

The Pod must run on a node in either us-east-1a or us-east-1b that also has the SSD label. If no eligible node satisfies every requirement and has enough available resources, the Pod remains Pending.

These requirements are checked when the Pod is scheduled. The IgnoredDuringExecution part means Kubernetes does not evict a running Pod solely because a node label later changes. A replacement Pod can remain Pending if labels, eligible zones, or available capacity have changed since the original placement.

Preferred node affinity

spec:
  affinity:
    nodeAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
        - weight: 1
          preference:
            matchExpressions:
              - key: "node.kubernetes.io/networking-type"
                operator: In
                values:
                  - fast
        - weight: 50
          preference:
            matchExpressions:
              - key: "topology.kubernetes.io/zone"
                operator: In
                values:
                  - us-east-1a

The scheduler prefers nodes in us-east-1a but also considers fast networking nodes. Higher weight means higher preference priority.

Combining node affinity and taints

spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
          - matchExpressions:
              - key: "dedicated"
                operator: In
                values:
                  - database
  tolerations:
    - key: "dedicated"
      operator: "Equal"
      value: "database"
      effect: "NoSchedule"

This Pod requires the dedicated=database node label and tolerates the matching taint. Together, affinity selects the intended node pool and the toleration lets the Pod pass that pool’s taint check. Placement still depends on available resources and other scheduling constraints.

Pod Affinity and Anti-Affinity

Pod affinity places a Pod near matching Pods; pod anti-affinity steers it away from them. Required rules can leave a Pod Pending when no eligible topology domain has a matching peer or when the remaining nodes lack capacity.

Pod anti-affinity for high availability

spec:
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        - labelSelector:
            matchExpressions:
              - key: "app"
                operator: In
                values:
                  - web-frontend
          topologyKey: topology.kubernetes.io/zone

This prevents matching web-frontend Pods from sharing a zone when enough eligible zones and capacity are available. If those conditions change, a new or replacement Pod may remain Pending.

Pod affinity for co-location

spec:
  affinity:
    podAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        - labelSelector:
            matchExpressions:
              - key: "app"
                operator: In
                values:
                  - redis
          topologyKey: kubernetes.io/hostname

This requires the Pod to share a node with a matching Redis Pod. The kubernetes.io/hostname topology key identifies the node.

Preferred pod anti-affinity

Hard requirements may prevent scheduling if constraints cannot be satisfied. Use preferred for softer constraints:

spec:
  affinity:
    podAntiAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
        - weight: 100
          podAffinityTerm:
            labelSelector:
              matchExpressions:
                - key: "app"
                  operator: In
                  values:
                    - web-frontend
            topologyKey: topology.kubernetes.io/zone

The scheduler prefers to spread Pods across zones, but it can place them together when the preference cannot be met.

Topology Spread for HA

Topology spread constraints express how matching Pods should be distributed across topology domains. They control placement skew, but do not set a minimum availability level or guarantee replacement capacity.

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

The first constraint requires matching web-frontend Pods to stay within a skew of 1 across eligible zones. If no candidate node satisfies the constraint, the Pod remains Pending (DoNotSchedule).

The second constraint prefers spreading across nodes. If the preferred balance is unavailable, the scheduler can still place the Pod (ScheduleAnyway).

maxSkew explained

With six Pods and three eligible zones:

  • Zone A: 3 Pods
  • Zone B: 2 Pods
  • Zone C: 1 Pod

The maxSkew here is 2, because the largest and smallest counts differ by two. A maxSkew: 1 constraint would not allow this distribution for a new matching Pod. Even distribution would be two Pods per zone.

If zone C later becomes unavailable and the distribution is:

  • Zone A: 3 Pods
  • Zone B: 3 Pods
  • Zone C: 0 Pods

the existing Pods are not moved automatically. If no eligible node can accept a new Pod without violating maxSkew: 1, that Pod remains Pending until capacity or constraints change.

Priority Classes and Preemption

Pod priority affects scheduling order. Higher-priority Pods are considered before lower-priority Pods. If no node can fit a high-priority Pod, the scheduler may preempt lower-priority Pods to make room, subject to its scheduling rules.

Defining a priority class

apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
  name: high-priority
value: 100000
globalDefault: false
description: "Production workloads with high priority"

Using priority class

Once you define a PriorityClass, apply it to pods via the priorityClassName field in the pod spec:

spec:
  priorityClassName: high-priority

Priority values determine scheduling order. When a high-priority Pod cannot fit, the scheduler may select lower-priority Pods as preemption victims on a candidate node. Those victims are terminated to free resources; this is preemption.

Priority can help production workloads move ahead of batch jobs. If every team marks its service as critical, the scheduler has fewer lower-priority Pods to choose as victims and more Pods may remain Pending. Use a small set of priority tiers, such as production-high at 10000 and production-default at 5000.

Within the supported integer range, relative priority matters more than the exact values. A few clearly named tiers are easier to operate than many nearly identical classes. If you configure a global default, choose a non-critical class; Pods without an explicit priorityClassName then receive that priority.

System priority classes

Kubernetes has system priority classes:

  • system-cluster-critical (value 2000000000)
  • system-node-critical (value 2000001000)

Kubernetes reserves these classes for critical cluster components. Application workloads should use application-level priority classes.

Scheduling Profiles

Kubernetes v1.37.1 supports multiple scheduling profiles in one kube-scheduler process. Each profile has a distinct name and can use a different plugin configuration. This example names a second profile; by itself, the name does not impose a high-memory requirement or change placement rules.

apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
  - schedulerName: default-scheduler
  - schedulerName: high-memory-scheduler

Assign a Pod to a configured profile by setting schedulerName:

spec:
  schedulerName: high-memory-scheduler
  containers:
    - name: high-mem-app
      image: myapp:latest

The name must match a profile configured in the scheduler. A separate scheduler process or a custom plugin needs additional configuration and operational setup.

Trade-off Analysis

Feature Affinity/Anti-Affinity Topology Spread Constraints
Scope Pod-to-pod or pod-to-node Pods across topology domains
Matching Label selectors Label selectors
TopologyKey Any label (hostname, zone, etc.) Any label
Hard requirements requiredDuringScheduling... whenUnsatisfiable: DoNotSchedule
Soft preferences preferredDuringScheduling... whenUnsatisfiable: ScheduleAnyway
Explicit maxSkew No Yes — controls imbalance tolerance
Multiple constraints Multiple affinity rules Multiple topologySpreadConstraints entries
Failure handling Required rules can leave a Pod Pending; preferences do not block placement DoNotSchedule can leave a Pod Pending; ScheduleAnyway allows placement

Use topology spread to control balance across zones or nodes. Use affinity to express relationships between Pods or between Pods and node labels. Hard constraints can make placement impossible as labels, topology domains, or capacity change.

Observability Hooks for Scheduling

What to monitor

Track Pending Pods, scheduling duration, and preemption events to identify scheduling problems.

# Find Pods stuck in Pending (some may be waiting for image pulls or storage, not scheduling)
kubectl get pods --all-namespaces --field-selector=status.phase=Pending

# Check scheduling duration for recent pods
kubectl get events --all-namespaces --sort-by='.metadata.creationTimestamp' | grep Scheduled

# Watch for preemption events
kubectl get events --all-namespaces --sort-by='.metadata.creationTimestamp' | grep Preempt

# Check which nodes have what taints
kubectl get nodes -o json | jq '.items[].spec.taints'

Key metrics to track

  • Pending Pod count by namespace (alert if it remains above zero for more than five minutes)
  • Scheduling latency (time from pod creation to scheduled)
  • Preemption count (high preemption rates suggest resource pressure)
  • Node taints and workload tolerations (review whether intended workloads can use the intended nodes)

Diagnose a Pod that is Pending

# If you know the namespace, inspect the Pod and its FailedScheduling events
kubectl describe pod myapp-xxx -n production
kubectl get events -n production --field-selector=involvedObject.kind=Pod,involvedObject.name=myapp-xxx,reason=FailedScheduling --sort-by=.metadata.creationTimestamp

# If you do not know the namespace, find Pending Pods and list scheduler events cluster-wide
kubectl get pods --all-namespaces --field-selector=status.phase=Pending
kubectl get events --all-namespaces --field-selector=involvedObject.kind=Pod,reason=FailedScheduling --sort-by=.metadata.creationTimestamp

The all-namespaces event list includes the NAMESPACE and NAME columns. Use those values with kubectl describe pod POD_NAME -n NAMESPACE to inspect a specific Pod. Scheduler events use reason FailedScheduling; the Pod condition uses reason Unschedulable.

These commands apply to the failed placement cases in this section. They show which required affinity, taint, topology, or resource check prevented placement. A server-side dry run validates an object with the API server; it does not simulate scheduling.

Production Failure Scenarios

Required node or pod affinity can leave a Pod Pending when no eligible node satisfies every rule. The same can happen when labels or topology domains change, or when the remaining eligible nodes do not have enough capacity. For example, a replacement for a Pod requiring an SSD-labeled node in us-east-1a or us-east-1b cannot schedule if those labels are removed or the matching nodes are full.

requiredDuringSchedulingIgnoredDuringExecution is evaluated when the scheduler places a Pod. The IgnoredDuringExecution part means an already-running Pod is not evicted solely because its node labels change. Required pod affinity and anti-affinity have the same placement risk: changed Pod labels, missing matching Pods, unavailable topology domains, or capacity pressure can leave a new Pod Pending. Topology spread with whenUnsatisfiable: DoNotSchedule can also block a new Pod if no eligible domain can accept it within maxSkew. These rules do not move running Pods to repair the distribution.

Inspect a failed placement in its namespace with the commands below. If the namespace is unknown, list Pending Pods and FailedScheduling events across namespaces, then use the returned namespace with kubectl describe:

# Namespace known
kubectl describe pod myapp-xxx -n production
kubectl get events -n production --field-selector=involvedObject.kind=Pod,involvedObject.name=myapp-xxx,reason=FailedScheduling --sort-by=.metadata.creationTimestamp

# Namespace unknown
kubectl get pods --all-namespaces --field-selector=status.phase=Pending
kubectl get events --all-namespaces --field-selector=involvedObject.kind=Pod,reason=FailedScheduling --sort-by=.metadata.creationTimestamp

The event reason is FailedScheduling; the Pod condition reports Unschedulable. If hard affinity across several dimensions is too restrictive, change nonessential requirements to preferredDuringSchedulingIgnoredDuringExecution. Keep hard requirements for constraints that must not be violated.

Priority Preemption Causing Disruption

When a high-priority Pod cannot find a node, the scheduler may preempt lower-priority Pods to make room. Preemption can disrupt a workload, and the replacement Pod still needs an eligible node with enough capacity.

For controller-managed workloads, the controller creates replacement Pods after victims are deleted. Those replacements may remain Pending during resource pressure.

Set priority classes carefully. Do not assign the highest priority to every production workload. PodDisruptionBudgets are useful for voluntary eviction requests, but they are not a hard barrier against scheduler preemption.

The scheduler considers lower-priority Pods as potential victims and checks whether removing them could make the pending Pod schedulable. Victims are terminated to free resources. During a resource crunch, replacements can also remain Pending if there is no suitable capacity.

Detect preemption by reviewing scheduler events for preemption messages:

kubectl get events --all-namespaces --sort-by='.metadata.creationTimestamp' | grep Preempt

If you see the same priority class getting preempted repeatedly, that class is too aggressive for your cluster.

Leave gaps between priority levels; for example, high-priority at 10000 and medium-priority at 5000 gives room to add an intermediate class later. Configure PodDisruptionBudgets for voluntary eviction requests such as a node drain, but do not rely on them to prevent all preemption. If the scheduler cannot find another way to place a pending high-priority Pod, it may preempt a Pod even when that violates its PDB. Avoid making a high-priority class the global default, since Pods without an explicit priority would inherit it.

Do not assign system-cluster-critical to every production Deployment. During a node drain, kubectl drain sends voluntary eviction requests and obeys PDBs unless configured otherwise; where replacement Pods can run depends on available capacity and their scheduling rules. Reserve system priority classes for cluster-wide components such as DNS and networking plugins, and use application-level priority classes for regular workloads.

What a PodDisruptionBudget does

A PodDisruptionBudget limits voluntary disruptions that use the Eviction API, such as a normal kubectl drain. It does not guarantee that evicted Pods can be rescheduled, create replacement capacity, or protect a workload from involuntary node failure. Scheduler preemption is a separate mechanism: the scheduler tries to avoid violating a PDB when choosing victims, but this is best-effort and it may violate the budget if no other placement is available. See the official Pod disruptions and Pod priority and preemption documentation for Kubernetes v1.37.

Taint NoExecute Evicting Critical Pods

The NoExecute effect evicts existing Pods without a matching toleration and blocks new Pods that lack one.

If you apply a NoExecute taint to a node running a monitoring agent without a matching toleration, the agent is evicted too.

For planned taint changes, check affected workloads and add tolerations where they are needed. Use tolerationSeconds when a workload should remain bound to a failing or unreachable node for a limited time.

NoSchedule blocks new Pods without a matching toleration. NoExecute also triggers eviction of existing Pods without a matching toleration. Use NoExecute only when that eviction behavior is intended; NoSchedule is generally the right effect for reserving a node pool.

For the built-in not-ready and unreachable taints, Kubernetes adds a 300-second toleration by default. This example sets that period explicitly:

tolerations:
  - key: "node.kubernetes.io/not-ready"
    operator: "Exists"
    effect: "NoExecute"
    tolerationSeconds: 300 # five minutes before eviction begins
  - key: "node.kubernetes.io/unreachable"
    operator: "Exists"
    effect: "NoExecute"
    tolerationSeconds: 300

Kubernetes adds these tolerations by default unless the Pod or a controller sets them explicitly. DaemonSet Pods tolerate these taints indefinitely. These tolerations keep the Pod bound to an unhealthy or unreachable node for the configured period; they do not move it to another node during that time.

Safe node maintenance with NoExecute follows a specific sequence:

  1. Cordon the node first (marks it unschedulable, does not evict anything)
  2. Drain the node (uses voluntary eviction requests and respects PDBs)
  3. Apply the NoExecute taint for the maintenance window
  4. Do the maintenance work
  5. Remove the taint
  6. Uncordon the node

If you skip the drain and apply a NoExecute taint, taint-based eviction bypasses PDBs. The Pod’s toleration and termination grace period affect how long shutdown takes, but they do not make the eviction a PDB-controlled voluntary disruption.

If a monitoring DaemonSet needs to run on a node tainted dedicated=database:NoSchedule, add a matching toleration to that DaemonSet. The toleration allows placement on the node; it does not attract the DaemonSet to it.

Anti-Patterns

Too Many Hard Affinity Requirements

Many requiredDuringSchedulingIgnoredDuringExecution constraints can leave Pods Pending. Requiring a GPU, SSD, and a particular zone works only if a node has all three labels and enough available capacity.

Keep hard requirements minimal. Use preferences for everything else.

Hard requirements compound into impossibility because each one is an AND filter. If you have 3 GPU nodes, 5 SSD nodes, and 2 nodes in us-east-1a, the intersection might be 1 node or 0. The scheduler filters sequentially, so adding “zone us-east-1a AND disk SSD AND GPU” narrows the candidate pool at each step, not as a holistic calculation.

Several hard node affinity requirements deserve review. Keep only those that are necessary for the workload; make the rest preferences when placement can remain flexible.

Refactoring from 3 hard requirements to 1 hard + 2 soft looks like this:

# Before: 3 hard requirements — risky
affinity:
  nodeAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      nodeSelectorTerms:
        - matchExpressions:
            - key: "topology.kubernetes.io/zone"
              operator: In
              values: [us-east-1a]
            - key: "node.kubernetes.io/disktype"
              operator: In
              values: [ssd]
            - key: "gpu-workload"
              operator: Exists

# After: 1 hard (zone), 2 soft (SSD + GPU)
affinity:
  nodeAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      nodeSelectorTerms:
        - matchExpressions:
            - key: "topology.kubernetes.io/zone"
              operator: In
              values: [us-east-1a]
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 50
        preference:
          matchExpressions:
            - key: "node.kubernetes.io/disktype"
              operator: In
              values: [ssd]
      - weight: 50
        preference:
          matchExpressions:
            - key: "gpu-workload"
              operator: Exists

To diagnose whether a pod is over-constrained:

kubectl get pods --all-namespaces --field-selector=status.phase=Pending
kubectl describe pod POD_NAME -n NAMESPACE
kubectl get events --all-namespaces --field-selector=involvedObject.kind=Pod,involvedObject.name=POD_NAME,reason=FailedScheduling --sort-by=.metadata.creationTimestamp

Use the namespace from the Pending Pod list with kubectl describe. A FailedScheduling event identifies unmatched selectors or affinity requirements. Soft preferences affect scoring; they do not make a Pod unschedulable.

undocumented Taints

When operators add taints without documenting them, developers may find that their Pods no longer schedule on those nodes.

Maintain a taint inventory. Document which workloads tolerate which taints. Put tolerations in the workload manifests.

Run this periodically and save the output alongside your cluster configuration:

#!/bin/bash
echo "=== Node Taints ==="
kubectl get nodes -o json | jq -r '.items[] | "\(.metadata.name): \(.spec.taints // [] | map("\(.key)=\(.value):\(.effect)") | join(", "))"'
echo ""
echo "=== Pod Tolerations (workload manifests) ==="
kubectl get pods -A -o yaml | grep -A5 "tolerations:" | grep -E "(key:|effect:|operator:)"

Commit this output to your infrastructure repo on each cluster update. It creates an auditable trail of why nodes are reserved.

Pick a naming convention and stick to it. Something like team/<purpose>:NoSchedule or hardware/<type>:NoExecute makes taints self-documenting, so developers can guess the toleration from the name. Avoid generic keys like reserved or dedicated that carry no meaning and end up requiring a Slack message to decode.

Track at minimum:

Field Example What to record
Key team/payment Who owns the reservation
Value payment Workload type
Effect NoSchedule Scheduling vs eviction behavior
Reason “Dedicated payment processing nodes” Why it exists
Created date 2025-11-01 For audit trail
Expected removal “After payment cluster migration Q2” Prevents permanent taints

When a team provisions dedicated hardware, document the taint and add any matching tolerations to workload manifests in the same change. This gives developers the placement context they need when a Pod cannot schedule.

Skipping topologySpreadConstraints

podAntiAffinity is good but not precise for zone distribution. topologySpreadConstraints is explicit about how imbalance is measured and what happens when constraints cannot be satisfied. Use it for anything that matters.

Why podAntiAffinity alone falls short: required pod anti-affinity on kubernetes.io/hostname prevents matching Pods from sharing a node, but it does not balance them across zones. With enough nodes, ten replicas across three zones could still be split 7-3-0. A zone outage could then remove most of the available replicas.

topologySpreadConstraints adds the maxSkew parameter that explicitly controls this. With maxSkew: 1 and 10 replicas across 3 zones, the scheduler maintains at most 1 pod difference between any two zones (4-3-3 or 4-4-2, never 7-3-0).

When to skip topologySpreadConstraints:

  • Single-node clusters where zone distribution is meaningless
  • Pods that do not need HA (batch jobs, dev workloads)
  • Workloads where the controller itself handles distribution (StatefulSets with zone-aware volume provisioning)

For workloads that need both node separation and zone balance, use pod anti-affinity on kubernetes.io/hostname with a topology spread constraint on topology.kubernetes.io/zone. Each hard constraint reduces the set of eligible placements, so check that enough nodes and zones remain for all replicas.

Example combining both:

spec:
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        - labelSelector:
            matchExpressions:
              - key: "app"
                operator: In
                values: [web-frontend]
          topologyKey: kubernetes.io/hostname
  topologySpreadConstraints:
    - maxSkew: 1
      topologyKey: topology.kubernetes.io/zone
      whenUnsatisfiable: DoNotSchedule
      labelSelector:
        matchLabels:
          app: web-frontend

The pod anti-affinity prevents matching Pods from sharing a node, while the topology spread constraint limits zone imbalance at scheduling time. Neither rule guarantees that only one replica will be lost in a zone failure or that replacement capacity will be available.

Interview Questions

1. How do taints and tolerations work together to control pod placement?

Expected answer points:

  • Taints are applied to nodes and repel Pods without matching tolerations
  • Tolerations allow a Pod to use a matching tainted node, but do not attract it or guarantee placement
  • Taint effects: NoSchedule (prevent scheduling), PreferNoSchedule (soft repel), NoExecute (evict existing pods)
  • The Exists operator matches any value for a key; Equal requires an exact match
  • Use case: reserving GPU nodes for ML workloads by tainting with gpu-workload:NoSchedule
2. What is the difference between hard and soft node affinity?

Expected answer points:

  • Hard affinity (requiredDuringSchedulingIgnoredDuringExecution) enforces requirements strictly
  • Soft affinity (preferredDuringSchedulingIgnoredDuringExecution) prefers but does not require
  • Hard requirements cause pods to stay Pending if unsatisfied; soft preferences are best-effort
  • Soft affinity has a weight property (1-100) that influences scoring relative to other preferences
  • Use hard affinity for strict requirements like zone placement; soft for optimization
3. How does topology spread constraints differ from pod anti-affinity?

Expected answer points:

  • topologySpreadConstraints provides explicit maxSkew control for balanced distribution
  • Pod anti-affinity expresses relationships but does not measure imbalance directly
  • topologySpreadConstraints supports whenUnsatisfiable: DoNotSchedule vs ScheduleAnyway for hard vs soft constraints
  • maxSkew measures the difference in pod count between any two topology domains
  • Use topologySpreadConstraints when balanced zone distribution is critical; pod anti-affinity for co-location
4. What happens when a pod with hard anti-affinity cannot find a satisfying node?

Expected answer points:

  • The Pod stays Pending until constraints or available capacity change
  • kubectl describe pod shows FailedScheduling events and messages about the unsatisfied constraint
  • The scheduler event reason is FailedScheduling; the PodScheduled condition reason is Unschedulable
  • Use kubectl get events -A --field-selector reason=FailedScheduling,involvedObject.kind=Pod to find scheduler events across namespaces
  • Solution is either to relax constraints (preferred) or add more nodes matching requirements
5. How does NoExecute taint effect differ from NoSchedule?

Expected answer points:

  • NoSchedule only prevents new pods from scheduling on the tainted node; existing pods are unaffected
  • NoExecute evicts existing pods that do not tolerate the taint from the node
  • NoExecute can optionally include tolerationSeconds for a grace period before eviction
  • Use NoSchedule to reserve a node pool; use NoExecute when existing untolerated Pods should also be evicted
  • NoExecute taint-based eviction is not governed by PodDisruptionBudgets
6. What is maxSkew in topologySpreadConstraints and how is it calculated?

Expected answer points:

  • maxSkew defines the maximum allowed difference in pod count between any two topology domains
  • Calculation: (max pod count in any zone) minus (min pod count in any zone)
  • With 6 pods and 3 zones (3, 2, 1): maxSkew is 2, which violates maxSkew: 1
  • The scheduler tries to place pods to keep maxSkew within the limit during new pod scheduling
  • When unsatisfiable with DoNotSchedule, pods stay Pending; with ScheduleAnyway, they schedule anyway
7. How do priority classes affect pod scheduling order?

Expected answer points:

  • Higher priority pods schedule before lower priority pods when resources are constrained
  • When a high-priority pod cannot find a node, the scheduler may preempt (evict) lower priority pods
  • For controller-managed workloads, replacement Pods are created but may remain Pending if no capacity is available
  • system-cluster-critical and system-node-critical are reserved for critical cluster components
  • Use PDBs for voluntary eviction requests; the scheduler only makes a best-effort attempt to respect them during preemption
8. When would you use a custom scheduler instead of the default scheduler?

Expected answer points:

  • Use a custom scheduler when workloads have specialized placement requirements the default scheduler cannot express
  • Examples: GPU binding to specific GPU devices, NUMA-aware scheduling, geographic constraints
  • Run multiple schedulers side-by-side and assign pods via schedulerName field
  • Custom schedulers need their own leader election setup for HA if multiple replicas run
  • For most cases, the default scheduler with affinity/taints/tolerations is sufficient
9. How does combining node affinity with taints and tolerations work in practice?

Expected answer points:

  • A node can have both a taint (to repel untolerated pods) and labels (for affinity matching)
  • A Pod can have both a toleration and node affinity to match a dedicated node pool
  • The toleration allows the Pod past the taint check; required node affinity selects matching nodes
  • Neither rule guarantees placement if labels change or the nodes lack capacity
  • Example: dedicated database node with taint dedicated=database:NoSchedule and label dedicated=database
  • Pod tolerates the taint and has requiredDuringScheduling affinity to the dedicated label
10. What observability signals indicate scheduling problems in production?

Expected answer points:

  • Pending pod count by namespace: alert if > 0 for more than 5 minutes
  • Scheduling latency: time from pod creation to scheduled, watch for increasing latency
  • Preemption events: high preemption rates indicate resource pressure
  • Node taint coverage: ensure critical workloads tolerate all taints, check via kubectl get nodes -o json
  • Scheduler events and logs show scheduling decisions and failures
11. What is the difference between podAntiAffinity and nodeAffinity?

Expected answer points:

  • nodeAffinity matches against node labels, expressing relationships between pods and nodes
  • podAntiAffinity matches against pod labels, expressing relationships between pods
  • podAntiAffinity can keep matching Pods apart across a topology such as zones or nodes
  • nodeAffinity matches node labels; topologyKey is used by pod affinity and topology spread constraints
  • Combine both to spread pods across zones while landing on nodes with specific hardware
12. How do you prevent over-constrained clusters from having pods stuck in Pending?

Expected answer points:

  • Audit hard affinity requirements and convert non-critical ones to preferred
  • Reserve hard requirements for true invariants like regulatory zone requirements
  • Monitor pending pods and set alerts before they accumulate
  • Use preferredDuringSchedulingIgnoredDuringExecution with weight 1 for soft preferences
  • When adding new constraints, test in staging first with realistic pod counts
13. How does the scheduler filter and score phases work?

Expected answer points:

  • Filtering removes nodes that cannot run the pod: resource constraints, taints, node selectors
  • Scoring ranks remaining nodes based on affinity rules, resource utilization, topology spread
  • The scheduler binds the pod to the highest-scoring node after both phases
  • If no nodes pass filtering, the pod stays Pending with reason Unschedulable
  • Custom schedulers can replace or supplement these plugins
14. What is the purpose of tolerationSeconds in NoExecute tolerations?

Expected answer points:

  • tolerationSeconds specifies how long a pod tolerates a NoExecute taint before being evicted
  • If not specified, the pod is evicted immediately when the taint is applied
  • With tolerationSeconds: 3600, the pod has 1 hour before eviction if the node gets tainted
  • This controls how long a Pod stays bound to a node with a matching NoExecute taint before eviction begins
  • It does not move the Pod to another node during the toleration period
15. How does topologyKey affect the meaning of topology spread?

Expected answer points:

  • topologyKey is the label key that defines the topology domain for spreading
  • topology.kubernetes.io/zone treats each availability zone as a domain
  • kubernetes.io/hostname treats each node as a topology domain
  • Custom labels can define other topology boundaries like rack or region
  • All pods with the same labelSelector are considered together for distribution across topologyKey domains
16. What is the tradeoff between using podAntiAffinity requiredDuringScheduling vs preferredDuringScheduling?

Expected answer points:

  • requiredDuringScheduling is a hard requirement: unsatisfiable constraints leave pods Pending
  • preferredDuringScheduling is a soft preference: scheduler tries but proceeds if impossible
  • Use required for strict HA requirements like spreading replicas across zones
  • Use preferred when perfect spread is nice-to-have but not critical
  • preferred with high weight (100) approaches required behavior while remaining softer
17. How do you configure pods to spread across zones while preferring same-node placement for cache?

Expected answer points:

  • Use topologySpreadConstraints with maxSkew: 1 and topologyKey: topology.kubernetes.io/zone for zone distribution
  • Use pod affinity when the cache layer should prefer same-node placement
  • With multiple constraints, the scheduler finds a node satisfying all constraints
  • Pod anti-affinity on kubernetes.io/hostname can prefer keeping cache replicas on different nodes
  • The zone spread constraint limits imbalance for new placement but does not guarantee recovery after a zone failure
18. Why might a pod with a PVC fail to schedule even after the node is uncordoned?

Expected answer points:

  • PersistentVolumes are zone-specific in most cloud providers (EBS in AWS, PD in GCP)
  • If the PVC is bound to a volume in a different zone, the pod cannot start on a node in another zone
  • Use volumeBindingMode: WaitForFirstConsumer in StorageClass to delay binding until scheduling
  • The scheduler then places the pod in the same zone as the volume
  • Check the Pod and its events with kubectl describe pod POD_NAME -n NAMESPACE
19. How does the scheduler decide which node is best when multiple pass filtering?

Expected answer points:

  • Scoring plugins rank nodes based on multiple criteria: affinity preferences, resource utilization, topology spread
  • Each scoring plugin returns a score; the scheduler sums them weighted by plugin priority
  • Nodes with higher total scores are preferred
  • Affinity rules contribute to scoring; preferredDuringScheduling weight determines influence
  • The scheduler picks the node with the highest score and binds the pod to it
20. What happens during cluster upgrades when nodes are drained and pods have NoExecute tolerations?

Expected answer points:

  • kubectl drain cordons a node and sends voluntary eviction requests that respect PDBs
  • Node taint-based NoExecute evictions are separate and are not controlled by PDBs
  • Pods tolerate node.kubernetes.io/not-ready or node.kubernetes.io/unreachable for the configured period, if those taints are applied
  • Add tolerations for cluster-level taints like node.kubernetes.io/not-ready:NoExecute
  • The drain command waits for pods to terminate; force deletion with --force for stuck pods

Further Reading

Official Documentation

Articles and Guides

Conclusion

Kubernetes scheduling gives you controls for Pod placement. Node taints repel Pods without matching tolerations; tolerations only allow a Pod to use a tainted node. Node and pod affinity can require or prefer relationships, while topology spread constraints can limit placement skew across failure domains.

These mechanisms can be combined. For example, taints and tolerations can reserve a GPU node pool, while node affinity selects it and topology spread limits zone imbalance. Hard requirements can leave new or replacement Pods Pending when labels, topology, or capacity change.

Priority classes give higher-priority workloads precedence in the scheduling queue. Preemption may free capacity by terminating lower-priority Pods, but it cannot guarantee that a Pod will have an eligible node.

For more on keeping applications highly available, see the High Availability post.

Category

Related Posts

Container Security: Image Scanning and Vulnerability Risks

Implement comprehensive container security: from scanning images for vulnerabilities to runtime security monitoring and secrets protection.

#container-security #docker #kubernetes

Deployment Strategies: Rolling, Blue-Green, Canary

Compare and implement deployment strategies—rolling updates, blue-green deployments, and canary releases—to reduce risk and enable safe production releases.

#deployment #devops #kubernetes

Developing Helm Charts: Templates, Values, and Testing

Create production-ready Helm charts with Go templates, custom value schemas, and testing using Helm unittest and ct.

#helm #kubernetes #devops