Topology Spread vs Pod Anti-Affinity
two ways to survive losing a node
Cloud infrastructurecloud infrastructure / Kubernetes scheduling
Same goal, very different contracts
You run 6 replicas and want them across 3 zones, not stacked on one node. Kubernetes gives you two tools for this and they are not interchangeable.
Pod anti-affinity is a rule about pairs: "don't put me where a pod matching this selector already is."
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels: {app: api}
topologyKey: kubernetes.io/hostname
Topology spread is a rule about counts: "keep the per-domain difference within maxSkew."
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels: {app: api}
The maxSkew arithmetic
Skew is max(matching pods in any domain) - min(...). With 3 zones and maxSkew: 1, 6 replicas can only land 2/2/2. A 7th makes 3/2/2 legal — 3/3/1 still is not.
The catch: min is computed only over domains the scheduler can see. A zone with no nodes carrying that label is not a domain at all, so a 2-zone cluster gives you a perfectly "balanced" 3/3/0.
Which one to reach for
- hostname + "at most one per node" → anti-affinity, required. It is an absolute cap, not a balance.
- zone + "spread evenly" → topology spread. Anti-affinity cannot express 2-per-zone; per domain it is all-or-nothing.
- Both together — spread across zones, anti-affinity on hostname — is common and correct.
The three that bite
whenUnsatisfiable: ScheduleAnywaydemotes the constraint to a scoring hint. Under pressure it will put 5 pods in one zone and never tell you. Most people copy this line from the docs and believe they are protected.DoNotScheduleconverts imbalance into Pending pods. Zone c's nodes fill up and your rollout stalls at 4/6 ready. That is the real tradeoff: the spread's availability vs the capacity's.IgnoredDuringExecutionappears in every one of these names. Nothing rebalances afterwards. Drain a node, pods move elsewhere, node returns empty — the skew persists until the next rollout. Run the descheduler if that matters.
The expensive one
Required anti-affinity is evaluated pod-against-pod: for each candidate node the scheduler checks existing matching pods. On a 500-node cluster with thousands of matching pods that filter cost scales with pods × nodes, and scheduling latency goes from milliseconds to seconds. Topology spread counts per domain instead, which is far cheaper. When both would work, prefer spread.
Your exercise
A 3-zone cluster, a Deployment of 4 replicas, maxSkew: 1, DoNotSchedule, zone topologyKey.
- Which placements are legal?
- Scale to 5 while one zone's nodes are full. What happens, and what does
kubectl describe podshow in Events? - Switch to
ScheduleAnywayand answer 2 again.