TExcelTAD
Home › Kubernetes › Scheduling: Affinity, Taints & Tolerations

Scheduling: Affinity, Taints & Tolerations

The kube-scheduler picks a node for every new Pod in two phases:

  1. Filter: drop nodes that can't run the Pod (not enough requested CPU/memory, wrong labels, untolerated taints, port conflicts, volume zone mismatch).
  2. Score: rank the remaining nodes (spread replicas, prefer nodes matching preferred affinity, balance resource usage) and pick the highest.

If no node passes the filter, the Pod stays Pending and the event explains why: 0/4 nodes are available: 2 Insufficient memory, 1 node(s) had untolerated taint {gpu: true}, 1 node(s) didn't match Pod's node affinity/selector.

You influence both phases with these tools:

Tool Set on Effect
nodeSelector Pod Only nodes with these labels (hard)
Node affinity Pod Hard (required…) or soft (preferred…) rules on node labels, with operators
Pod affinity / anti-affinity Pod Place near / away from other Pods (same node, same zone)
Taints Node Repel Pods that don't tolerate them
Tolerations Pod Allow (not force) placement on tainted nodes
topologySpreadConstraints Pod Spread replicas evenly across zones/nodes
priorityClassName Pod Higher-priority Pods may preempt lower ones

Node selectors and node affinity

yaml
spec:
  nodeSelector:
    kubernetes.io/arch: amd64
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
          - matchExpressions:
              - {key: topology.kubernetes.io/zone, operator: In, values: [eu-west-1a, eu-west-1b]}
      preferredDuringSchedulingIgnoredDuringExecution:
        - weight: 80
          preference:
            matchExpressions:
              - {key: node.kubernetes.io/instance-type, operator: In, values: [m7i.large]}

"IgnoredDuringExecution" means: if node labels change later, already-running Pods stay put.

Taints and tolerations

A taint is key=value:effect on a node:

Effect Meaning
NoSchedule New Pods without a matching toleration are not scheduled here
PreferNoSchedule Avoid if possible (soft)
NoExecute Also evicts running Pods that don't tolerate it (optionally after tolerationSeconds)
bash
kubectl taint nodes gpu-1 gpu=true:NoSchedule
kubectl taint nodes gpu-1 gpu=true:NoSchedule-      # trailing "-" removes it
yaml
tolerations:
  - key: gpu
    operator: Equal       # or Exists (matches any value)
    value: "true"
    effect: NoSchedule

Note: A toleration only permits a Pod on a tainted node. To dedicate GPU nodes to GPU Pods, combine a taint (keeps others out) with node affinity (pulls GPU Pods in).

A scheduler you can run

This model implements the filter phase (requests, node selector, required affinity, taints) and a simple score (preferred-affinity weight plus the share of CPU left free), parsing the Pod spec from YAML:

python · try it yourself
import yaml

nodes = [
    {"name": "node-a", "labels": {"zone": "a", "disk": "ssd"}, "free": {"cpu": 1500, "mem": 4096}, "taints": []},
    {"name": "node-b", "labels": {"zone": "b", "disk": "hdd"}, "free": {"cpu": 3000, "mem": 8192}, "taints": []},
    {"name": "node-c", "labels": {"zone": "a", "disk": "ssd", "gpu": "true"}, "free": {"cpu": 4000, "mem": 16384},
     "taints": [{"key": "gpu", "value": "true", "effect": "NoSchedule"}]},
    {"name": "node-d", "labels": {"zone": "c", "disk": "ssd"}, "free": {"cpu": 500, "mem": 1024}, "taints": []},
]

pod = yaml.safe_load("""
name: api
requests: {cpu: 1000, mem: 2048}
nodeSelector: {disk: ssd}
required:
  - {key: zone, operator: In, values: [a, b, c]}
preferred:
  - weight: 50
    match: {key: zone, operator: In, values: [a]}
tolerations: []
""")

def expr_ok(labels, e):
    v = labels.get(e["key"])
    return v in e["values"] if e["operator"] == "In" else v not in e["values"]

def tolerated(taint, tolerations):
    return any(t["key"] == taint["key"] and t.get("effect", taint["effect"]) == taint["effect"]
               and (t.get("operator") == "Exists" or t.get("value") == taint["value"]) for t in tolerations)

def filter_node(n, pod):
    if any(n["free"][r] < pod["requests"][r] for r in pod["requests"]):
        return "Insufficient " + ", ".join(r for r in pod["requests"] if n["free"][r] < pod["requests"][r])
    if any(n["labels"].get(k) != v for k, v in pod.get("nodeSelector", {}).items()):
        return "didn't match nodeSelector"
    if not all(expr_ok(n["labels"], e) for e in pod.get("required", [])):
        return "didn't match node affinity"
    for t in n["taints"]:
        if t["effect"] == "NoSchedule" and not tolerated(t, pod.get("tolerations", [])):
            return f"untolerated taint {{{t['key']}: {t['value']}}}"
    return None

def score(n, pod):
    s = sum(p["weight"] for p in pod.get("preferred", []) if expr_ok(n["labels"], p["match"]))
    s += round(100 * (n["free"]["cpu"] - pod["requests"]["cpu"]) / n["free"]["cpu"]) // 2
    return s

def schedule(pod):
    feasible = []
    for n in nodes:
        reason = filter_node(n, pod)
        print(f"  {n['name']}: {'feasible, score ' + str(score(n, pod)) if reason is None else reason}")
        if reason is None:
            feasible.append(n)
    if not feasible:
        return "Pending"
    return max(feasible, key=lambda n: score(n, pod))["name"]

print("api ->", schedule(pod))
pod["tolerations"] = [{"key": "gpu", "operator": "Exists", "effect": "NoSchedule"}]
print("api with gpu toleration ->", schedule(pod))
  node-a: feasible, score 66
  node-b: didn't match nodeSelector
  node-c: untolerated taint {gpu: true}
  node-d: Insufficient cpu, mem
api -> node-a
  node-a: feasible, score 66
  node-b: didn't match nodeSelector
  node-c: feasible, score 87
  node-d: Insufficient cpu, mem
api with gpu toleration -> node-c

Without the toleration, node-a was the only feasible node: node-b failed the disk: ssd selector, node-c's taint repelled the Pod and node-d was too small. With the toleration, node-c becomes feasible and wins: it is in the preferred zone and has the most CPU left over.

Spreading replicas

Running all replicas on one node (or in one zone) defeats the purpose of replicas. Pod anti-affinity and topology spread constraints prevent it:

yaml
topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: DoNotSchedule
    labelSelector:
      matchLabels: {app: api}

maxSkew: 1 means the number of matching Pods in any two zones may differ by at most 1. Placing replicas one at a time:

python · try it yourself
zones = {"zone-a": 0, "zone-b": 0, "zone-c": 0}
capacity = {"zone-a": 10, "zone-b": 1, "zone-c": 10}   # zone-b is nearly full
max_skew = 1

for replica in range(1, 8):
    placed = None
    for zone in sorted(zones, key=lambda z: (zones[z], z)):
        if zones[zone] >= capacity[zone]:
            continue
        counts = dict(zones)
        counts[zone] += 1
        if max(counts.values()) - min(counts.values()) <= max_skew:
            placed = zone
            break
    if placed is None:
        print(f"replica {replica}: Pending (would violate maxSkew={max_skew})")
        continue
    zones[placed] += 1
    print(f"replica {replica}: {placed:6} -> {zones}")
replica 1: zone-a -> {'zone-a': 1, 'zone-b': 0, 'zone-c': 0}
replica 2: zone-b -> {'zone-a': 1, 'zone-b': 1, 'zone-c': 0}
replica 3: zone-c -> {'zone-a': 1, 'zone-b': 1, 'zone-c': 1}
replica 4: zone-a -> {'zone-a': 2, 'zone-b': 1, 'zone-c': 1}
replica 5: zone-c -> {'zone-a': 2, 'zone-b': 1, 'zone-c': 2}
replica 6: Pending (would violate maxSkew=1)
replica 7: Pending (would violate maxSkew=1)

Because zone-b is full, the spread can't stay within skew 1 forever, and DoNotSchedule leaves the extra replicas Pending. With whenUnsatisfiable: ScheduleAnyway they would be placed with a penalty instead.

Test yourself

A node has the taint gpu=true:NoSchedule. Which Pods can be scheduled on it?

  1. Any Pod
  2. Only Pods with a matching toleration
  3. Only DaemonSet Pods
  4. None

Does a toleration force a Pod onto the tainted node?

  1. Yes
  2. No, it only allows it; use node affinity to attract it
  3. Only with NoExecute
  4. Only for GPUs

What does requiredDuringSchedulingIgnoredDuringExecution imply when node labels change later?

  1. Running Pods are evicted
  2. Running Pods keep running
  3. The node is drained
  4. The Pod restarts