Affinity, Anti-Affinity, Taints, and Tolerations: Controlling Where Pods Land

Taints and tolerations in Kubernetes, plus nodeSelector, node affinity, pod anti-affinity and topology spread for dedicated pools.

Executive Summary: Placement controls fall into two groups that are easy to confuse. Affinity rules live on the pod and attract it to nodes, or to or away from other pods. Taints live on the node and repel every pod that lacks a matching toleration. To dedicate a node pool, you need both: a taint to keep other pods off, and affinity so the intended pods go there. For high availability, topology spread constraints are usually a better tool than pod anti-affinity. Keep rules as soft as you can, because every hard rule is a way for a pod to stay Pending.
Isometric nodes with colour-coded taint tags and pods routed to matching nodes by dashed lines

The scheduler, introduced in the control plane article, picks a node for each new pod in two phases. Filtering removes nodes that cannot run the pod: not enough allocatable resources for its requests, a taint it does not tolerate, a required affinity rule it fails. Scoring ranks the remaining nodes using preferences, spreading and resource balance. Every one of these mechanisms adds filters or scores.

The tools at a glance

Mechanism Defined on Effect Typical use
nodeSelector Pod Only nodes with these exact labels Simple targeting: arm64 nodes
Node affinity Pod Required or preferred node label expressions Instance types, zones, spot vs on-demand
Pod affinity Pod Near pods with given labels Co-locate a cache with its app
Pod anti-affinity Pod Away from pods with given labels Never two replicas on one node
Topology spread Pod Even distribution across a topology key Balance replicas across zones and nodes
Taints and tolerations Node and pod Repel pods without a toleration Dedicated GPU pools, control plane nodes

Node affinity

affinity:
  nodeAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      nodeSelectorTerms:
        - matchExpressions:
            - key: kubernetes.io/arch
              operator: In
              values: ["amd64", "arm64"]
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 80
        preference:
          matchExpressions:
            - key: karpenter.sh/capacity-type
              operator: In
              values: ["spot"]

The long names explain themselves. required... is a filter and preferred... adds score. IgnoredDuringExecution means that if a node’s labels change later, running pods stay where they are. Operators include In, NotIn, Exists, DoesNotExist, Gt and Lt, and terms within nodeSelectorTerms are combined with OR, while expressions inside one term are combined with AND.

Prefer well-known labels that the kubelet and cloud providers set, such as kubernetes.io/arch, topology.kubernetes.io/zone and node.kubernetes.io/instance-type, over hand-applied ones that disappear when a node is replaced.

Spreading replicas: topology spread first

The classic way to keep replicas apart is pod anti-affinity:

affinity:
  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          topologyKey: kubernetes.io/hostname
          labelSelector:
            matchLabels:
              app: checkout

Anti-affinity only says “not together”. A required version also caps you at one replica per node, so scaling past the node count leaves pods Pending. It is also expensive for the scheduler in large clusters. Topology spread constraints express what you usually want, an even distribution:

topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: DoNotSchedule
    labelSelector:
      matchLabels:
        app: checkout
    matchLabelKeys: ["pod-template-hash"]
  - maxSkew: 1
    topologyKey: kubernetes.io/hostname
    whenUnsatisfiable: ScheduleAnyway
    labelSelector:
      matchLabels:
        app: checkout

The first constraint keeps zones within one pod of each other and is a hard rule; the second spreads across nodes as a preference. maxSkew is the largest allowed difference in matching pods between any two domains. matchLabelKeys with pod-template-hash, beta and on by default since Kubernetes 1.27, counts only pods from the current ReplicaSet, so a rolling update is not skewed by old pods that are about to disappear.

Two cautions. Spreading only happens at scheduling time; the scheduler never moves running pods, so after a zone outage and recovery pods can stay unbalanced until they are recreated, unless you run the descheduler. And a hard zone rule interacts with storage: a pod bound to a zonal volume can only go to that zone, so make sure StorageClasses use WaitForFirstConsumer binding.

Taints and tolerations

A taint marks a node as unsuitable for pods that do not explicitly tolerate it:

kubectl taint nodes gpu-node-1 nvidia.com/gpu=true:NoSchedule

# remove it
kubectl taint nodes gpu-node-1 nvidia.com/gpu=true:NoSchedule-
Effect New pods without toleration Running pods without toleration
NoSchedule Not scheduled Keep running
PreferNoSchedule Avoided if possible Keep running
NoExecute Not scheduled Evicted, after tolerationSeconds if set

A pod that should run there declares a toleration:

tolerations:
  - key: nvidia.com/gpu
    operator: Equal
    value: "true"
    effect: NoSchedule

Kubernetes uses taints itself. Control plane nodes carry node-role.kubernetes.io/control-plane:NoSchedule. When a node becomes unreachable or not ready, the node controller adds NoExecute taints, and every pod gets a default toleration of 300 seconds for them, which is why pods on a failed node take about five minutes to be replaced. Lowering tolerationSeconds for those taints speeds up failover for stateless apps, at the risk of churn during brief network blips.

Dedicated node pools need both halves

The most common mistake is to treat a toleration as an attraction. A toleration only permits a pod onto a tainted node; it does not send it there. A dedicated pool therefore needs:

  1. A taint on the pool’s nodes, so ordinary pods stay off.
  2. A label on the same nodes, such as pool=gpu.
  3. On the intended pods, a toleration for the taint and a node affinity or nodeSelector for the label.
spec:
  nodeSelector:
    pool: gpu
  tolerations:
    - key: nvidia.com/gpu
      operator: Exists
      effect: NoSchedule
  containers:
    - name: trainer
      image: ghcr.io/acme/trainer:1.4.0
      resources:
        limits:
          nvidia.com/gpu: 1

Remember DaemonSets: node agents need tolerations for every taint you add, or the new pool silently runs without logging or monitoring, as the StatefulSets and DaemonSets article noted.

Debugging Pending pods

kubectl describe pod shows a FailedScheduling event that summarizes why each node was rejected, for example:

0/9 nodes are available: 3 node(s) had untolerated taint {nvidia.com/gpu: true},
4 node(s) didn't match pod topology spread constraints,
2 Insufficient memory. preemption: 0/9 nodes are available...

Read it as a count per reason. If every node fails for a scheduling rule rather than resources, the rules are too strict for the cluster you have. If you use a cluster autoscaler, check that it can create nodes satisfying the rule; Cluster Autoscaler and Karpenter both simulate affinity and taints, but only for node groups or pools they are configured to provision.

Frequently Asked Questions

What is the difference between taints and node affinity?

Node affinity is set on pods and attracts them to nodes with certain labels. Taints are set on nodes and repel any pod without a matching toleration. Affinity says where a pod wants to go; taints say which pods a node refuses.

Does a toleration make a pod run on the tainted node?

No. A toleration only allows the pod onto a tainted node; the scheduler may still place it elsewhere. To dedicate nodes to a workload, combine a taint on the nodes with node affinity or a nodeSelector on the pods.

Should I use pod anti-affinity or topology spread constraints?

For spreading replicas across nodes or zones, topology spread constraints are usually better: they allow an even distribution with more replicas than domains and scale better in large clusters. Pod anti-affinity is still useful for keeping two different applications apart.

Why is my pod stuck in Pending?

Run kubectl describe pod and read the FailedScheduling event. It lists how many nodes failed each check, such as insufficient CPU or memory, untolerated taints, affinity mismatches or spread constraints, which points to the rule or resource to change.

Soft by default, hard where it counts

Use zone spreading as a hard rule for anything that must survive a zone outage, node spreading as a preference, taints plus affinity for dedicated hardware, and little else. Each required rule shrinks the set of nodes a pod can use, and the scheduler can only work with the nodes you have. For the full reference, see the taints and tolerations documentation and the pod placement documentation. Related reading on this site: requests and limits.

Originally posted on 24 September 2024 and post last modified on 24 September 2024

DevOps High Availability Kubernetes Scheduling

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *