Q: What is topology spread constraints and when would you use it over pod anti-affinity?
Topology spread constraints tell the scheduler to distribute matching pods evenly across failure domains such as zones or nodes, within a tolerated difference called maxSkew.
Want to master this scenario in a live sandbox? KodeKloud's CKA & CKAD Hands-On Certification Track covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Direct Answer: <strong>Topology spread constraints</strong> tell the scheduler to distribute matching pods evenly across failure domains such as zones or nodes, within a tolerated difference called <code>maxSkew</code>. Pod anti-affinity instead repels pods from each other, which is all-or-nothing when set as required. Interviewers ask this to test high availability design: how do you keep replicas alive through a zone outage without making the Deployment unschedulable when replicas exceed domains? The short answer is to prefer spread constraints for even distribution and keep anti-affinity for strict separation rules.
How topology spread constraints work
The scheduler counts matching pods per topology domain and keeps the gap within maxSkew.
- topologyKey: the node label that defines a domain, commonly
topology.kubernetes.io/zoneorkubernetes.io/hostname. - maxSkew: the maximum allowed difference in matching pod count between the fullest and emptiest domain.
- whenUnsatisfiable:
DoNotSchedulekeeps the pod Pending,ScheduleAnywaytreats it as a soft preference. - labelSelector: selects which pods are counted; it must match the pods of the workload, otherwise the constraint counts nothing.
Spreading across zones and nodes
Combine a hard zone constraint with a soft node constraint for a typical web service.
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
namespace: prod
spec:
replicas: 6
selector:
matchLabels: {app: my-app}
template:
metadata:
labels: {app: my-app}
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels: {app: my-app}
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels: {app: my-app}
containers:
- name: app
image: registry.example.com/my-app:1.0.0
- Zone (hard): survive one zone loss with replicas balanced across zones.
- Node (soft): avoid stacking on one node but never block scheduling.
- minDomains: forces a minimum number of domains to be considered when used with
DoNotSchedule(check availability on your version, beta since 1.25 and stable in 1.30). - Rolling updates:
matchLabelKeyswithpod-template-hashkeeps old and new ReplicaSets from skewing each other (version dependent, enabled by default in recent releases).
Choosing between spread and anti-affinity
Both influence placement, but they express different intent.
# Anti-affinity: different workload separation
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels: {app: batch-worker}
topologyKey: kubernetes.io/hostname
- Anti-affinity required: at most one matching pod per domain. With 6 replicas and 3 zones, 3 pods stay Pending.
- Anti-affinity preferred: a weighted hint with no guaranteed balance, so skew can still grow.
- Spread constraints: allow several pods per domain while keeping counts balanced, so scale-out always works.
- Use anti-affinity when: you need strict exclusivity or separation between different workloads, for example never co-locating a noisy batch job with a latency-sensitive database.
- Scale note: inter-pod anti-affinity is more expensive for the scheduler in large clusters than spread constraints.
Verifying the distribution
Confirm real placement rather than trusting the manifest.
kubectl get pods -n prod -l app=my-app -o wide
kubectl get nodes -L topology.kubernetes.io/zone
kubectl describe pod <pending-pod> -n prod | grep -A3 FailedScheduling
- Node per pod: list pods with the node column and map nodes to zones.
- Zone labels: confirm nodes actually carry the topology label, since a missing label makes that node ineligible for the constraint.
- Pending reason:
describe podshowsdidn't match pod topology spread constraintswhen a hard rule blocks placement.
Limits and production practice
Spread is applied at scheduling time only.
- No rebalancing: pods are not moved after scale-down, node drain or failures, so skew can drift. The Descheduler (
RemovePodsViolatingTopologySpreadConstraint) can evict violators. - Cluster defaults: the scheduler can apply
defaultConstraintsthroughKubeSchedulerConfigurationfor pods that define none. - Autoscaling: combine with a PodDisruptionBudget, and remember Cluster Autoscaler or Karpenter must be able to add nodes in the needed zone.
- Stateful data: zonal PersistentVolumes can pin a pod to one zone and conflict with the constraint.
- Topology spread constraints keep matching pods evenly spread across zones or nodes within a maxSkew tolerance.
- I verify with kubectl get pods -o wide and node zone labels, and check FailedScheduling events for blocked pods.
- I pair them with a PodDisruptionBudget and the Descheduler, and keep anti-affinity only for strict separation between workloads.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- Using required pod anti-affinity per zone for a large Deployment Replicas beyond the number of domains stay Pending, while a spread constraint with maxSkew would place them evenly.
- A labelSelector that does not match the pod labels The scheduler counts zero pods per domain so the constraint never actually spreads anything.
- Assuming spread is maintained over time It is evaluated only at scheduling, so drains and scale-downs can leave a skewed layout without a descheduler.
- Using DoNotSchedule on a key some nodes lack Nodes without the topology label are ignored, which can concentrate pods or leave them Pending.