Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Kubernetes Topology Spread Constraints vs Pod Affinity and Anti-Affinity

maxSkew, topologyKey, and whenUnsatisfiable decide distribution across zones and nodes. Why required anti-affinity deadlocks at scale and spread degrades instead.

~5 min readKubernetes
#Kubernetes#Scheduling#Topology#High Availability
3D illustration of three zone platforms with evenly distributed pod cubes and a skew gauge between them

Quick Summary

Pod affinity and topology spread constraints both distribute pods across failure domains, and they differ in what they promise. Pod affinity says "put me near (or away from) pods matching this selector"; topology spread says "keep the counts across domains within this skew", which is a constraint on the distribution rather than on any single pod.

The fields that cause the most confusion: topologyKey is a node label (kubernetes.io/hostname, topology.kubernetes.io/zone), maxSkew is the largest allowed difference between the domain with the most matching pods and the one with the fewest, and whenUnsatisfiable decides whether the constraint blocks scheduling (DoNotSchedule) or merely informs the scores (ScheduleAnyway).

Pod anti-affinity with requiredDuringSchedulingIgnoredDuringExecution on kubernetes.io/hostname is the classic "one replica per node" rule, and it deadlocks at scale: once every node holds one matching pod, the next replica has nowhere to go. Topology spread with maxSkew: 1 and ScheduleAnyway degrades gracefully instead, which is why it replaced anti-affinity for replica spreading in most production manifests.

Basic Syntax & Core Signatures

yaml
apiVersion: apps/v1 kind: Deployment metadata: name: api spec: replicas: 6 selector: matchLabels: { app: api } template: metadata: labels: { app: api } spec: topologySpreadConstraints: - maxSkew: 1 topologyKey: topology.kubernetes.io/zone whenUnsatisfiable: DoNotSchedule labelSelector: matchLabels: { app: api } minDomains: 3 # penalty when fewer domains exist - maxSkew: 1 topologyKey: kubernetes.io/hostname whenUnsatisfiable: ScheduleAnyway labelSelector: matchLabels: { app: api } affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: topologyKey: kubernetes.io/hostname labelSelector: matchLabels: { app: api } containers: - name: api image: registry.example.com/shop/api:4.2.0
yaml
# "Run near the cache": pod affinity with a namespace restriction affinity: podAffinity: requiredDuringSchedulingIgnoredDuringExecution: - topologyKey: kubernetes.io/hostname labelSelector: matchLabels: { app: redis } namespaces: [cache] # default: the pod's own namespace namespaceSelector: {} # alternative: any labelled namespace
bash
kubectl get nodes -L topology.kubernetes.io/zone,kubernetes.io/hostname kubectl get pods -l app=api -o custom-columns=\ NAME:.metadata.name,NODE:.spec.nodeName,ZONE:.metadata.labels.topology\\.kubernetes\\.io/zone kubectl describe pod api-6c7d9f-abcde | grep -A3 "Topology Spread"

Key Comparison Table

ConstraintGuaranteesFails as
Pod affinity (required)Co-located with matching podsPending if no domain has a match
Pod anti-affinity (required)Never co-locatedPending when every node has one
Pod anti-affinity (preferred)Best effortSchedules anyway, unevenly
Topology spread DoNotScheduleSkew within maxSkewPending, with the skew in the event
Topology spread ScheduleAnywayBias toward balanceSchedules anywhere, warns of skew
nodeAffinity requiredOnly matching nodesPending with a node-affinity message
Topology spread fieldMeaningDefault
maxSkewAllowed difference between the fullest and emptiest domainrequired
topologyKeyNode label defining a domainrequired
whenUnsatisfiableHard or softrequired
labelSelectorWhich pods are countedrequired
minDomainsDomains below which the constraint counts as unsatisfiable1
nodeAffinityPolicyWhether to honour the pod's node affinity when countingHonor
nodeTaintsPolicyWhether to count tainted nodes as domainsIgnore
SymptomMeaning
Pending: node(s) didn't match pod anti-affinity rulesEvery candidate node already holds a match
Pending: skew messageA domain is over-full relative to another
Pods land in one zone despite spreadtopologyKey label missing on nodes
Rollout stalls at 1 pending podRequired anti-affinity with replicas above node count

Practical Edge Cases & Deep Dives

1. Anti-affinity deadlock and why spread replaced it

text
nodes: 3, replicas: 4, required anti-affinity on hostname -> one pod per node, 4th pod Pending forever

A rolling update makes it worse: the Deployment wants to surge a new pod onto a node that already holds a pod matching its own selector (the new pod's labels match too), so the surge pod cannot schedule and maxSurge has to be 0 or the rollout hangs. Topology spread with maxSkew: 1 and ScheduleAnyway allows the imbalance when the cluster genuinely cannot satisfy it, so a scale-up past node count still makes progress — unevenly, which is visible in the metrics rather than in a stuck pod.

2. minDomains and clusters smaller than the intended topology

A three-zone constraint on a two-zone cluster can never satisfy maxSkew: 1 with DoNotSchedule if minDomains: 3 is set — the scheduler treats the missing domain as an empty one and blocks. Without minDomains, the constraint evaluates only over existing domains and happily puts everything in two zones. Set minDomains when zone balance must be enforced and pods going Pending is the correct signal to add capacity.

bash
kubectl describe pod api-6c7d9f-abcde | sed -n '/Topology Spread/,+4p' # Node: ... -> minDomains: 3, found 2 domains, cannot satisfy maxSkew

3. nodeAffinityPolicy and nodeTaintsPolicy change the denominator

Since 1.26 the constraint honours the pod's own node affinity by default (Honor): nodes the pod could not run on anyway are excluded from the skew calculation. nodeTaintsPolicy: Ignore (the default) counts tainted nodes as domains, which over-constrains pods that avoid those nodes. Setting nodeTaintsPolicy: Honor makes the count match where the pod can actually go — the fix when a scale-up is blocked by "skew" on nodes nobody can use.

4. Zone spread with a StatefulSet still needs per-pod topology

Topology spread balances replicas; it does not make a StatefulSet's volumes zone-independent. Each PVC is bound to a zone through its PV, so a pod can only run where its disk lives, and the scheduler's spread constraint is silently secondary to the volume node affinity. Symptom: even distribution in the first deploy, then Pending pods after a scale-up in one zone.

yaml
# The scheduler reports which rule won 0/9 nodes are available: 6 node(s) had volume node affinity conflict, 3 node(s) didn't match pod topology spread constraints.

The durable pattern is a per-zone StatefulSet or a storage class that provisions in the node's zone with a matching spread constraint and enough zones to tolerate one failing.

5. Pod affinity across namespaces, and the cost of namespaceSelector

podAffinity defaults to the pod's own namespace. Reaching into another one needs either namespaces: [cache] (explicit list) or namespaceSelector. Both make the term depend on objects outside the pod's own tree, so an operator's cache namespace rename silently stops placement. Prefer a stable label on the target namespace and match on kubernetes.io/metadata.name, which is immutable.

Also note that pod affinity has a scheduling cost: the scheduler must index all pods matching the selector on every candidate node. Large clusters with thousands of pods and required pod affinity are measurably slower to schedule than ones using topology spread, which uses precomputed counts per domain.

Common Runtime & Configuration Mistakes

SymptomCauseFix
Pending after scale-up past node countRequired anti-affinityUse topology spread, or ScheduleAnyway
Rollout hangs at a surge podAnti-affinity against own selectormaxSurge: 0, or spread instead
Everything in one zonetopologyKey label absent from nodesLabel nodes; verify with -L
Skew message despite free capacityminDomains above existing domainsLower it, or add a zone
Counting tainted nodes as domainsnodeTaintsPolicy: IgnoreSet Honor
Pods spread but PVC-bound pods PendingVolume node affinity outweighs spreadZone-aligned storage per zone
Affinity matches nothing after a renameCross-namespace selectorMatch kubernetes.io/metadata.name
Co-location works only sometimesPreferred affinity is best effortRequired affinity for correctness
Scheduler slow with many replicasRequired pod affinity over big selectorsTopology spread
Constraint ignored by the schedulerOld API server, or field typo in the termCheck describe pod output

Both features are answered by the same question: which domain does this pod count against, and what happens when that domain is full? Choose DoNotSchedule only when a wrong placement is worse than no placement, and prefer spread over anti-affinity for anything whose replica count can grow.

Try matching browser tools

All tools

Small utilities that fit Kubernetes work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Kubernetes guides

More in Kubernetes

All Kubernetes guides

The guides filed next to this one in Kubernetes, in library order.