This guide shows Kubernetes operators how to spread a service’s pods evenly across nodes and availability zones (separate data centres in one cloud region), so one outage cannot take down every copy. By default, the scheduler, the part of Kubernetes that picks a node for each pod, places pods wherever they fit and can stack them all in one zone. The topologySpreadConstraints field prevents that with maxSkew, the largest allowed gap in pod count between the busiest and the emptiest group. A topologyKey names the node label that defines each group, such as a zone or a single node, and whenUnsatisfiable decides whether to hold the pod back or place it anyway. You will also learn the placement math, cluster-wide defaults, and how to fix pods stuck in Pending (waiting, never placed) because the rule can never be met.
What you’ll accomplish
- Spread a Deployment’s replicas evenly across zones with a hard constraint, and across nodes with a soft one.
- Read the skew calculation the scheduler performs, so you can predict placement instead of guessing.
- Choose deliberately between
DoNotScheduleandScheduleAnywayfor each domain level. - Set cluster-wide default constraints so workloads that never opted in still get sane spreading.
- Diagnose
FailedSchedulingevents that name topology spread, and tell a real constraint violation from a missing node label.
Prerequisites
- Kubernetes 1.19 or newer.
topologySpreadConstraintsreached GA in 1.19, so the core fields —maxSkew,topologyKey,whenUnsatisfiable,labelSelector— are available on any cluster you should still be running. - 1.30 or newer for
minDomains. It went GA in 1.30. On older clusters the field is silently dropped unless the feature gate is on. - 1.27 or newer for
matchLabelKeys, and 1.26 or newer fornodeAffinityPolicy/nodeTaintsPolicy. Both were beta and enabled by default from those releases. Check withkubectl explain pod.spec.topologySpreadConstraintson your actual cluster — if a field is missing from the output, your API server will drop it from the manifest without complaining. - Nodes carrying real topology labels. The well-known keys are
topology.kubernetes.io/zone,topology.kubernetes.io/region, andkubernetes.io/hostname. Cloud providers set the first two automatically; on bare metal or a self-built cluster you label the nodes yourself. - Enough nodes per domain to satisfy the constraint. Three zones with one node each cannot host a six-replica Deployment that also demands one pod per node.
kubectlwith permission to create Deployments and read nodes, plus node-level access if you intend to change the scheduler configuration.
How it works
The scheduler evaluates one constraint at a time, for each candidate node, and computes a number called the skew:
skew(D) = count(D) − min( count(d) for every eligible domain d )
Here count(D) is the number of pods in domain D that match the constraint’s labelSelector in the same namespace, counting the pod being placed. Eligible domains are those containing at least one node that passes the pod’s node affinity and node selector. If placing the pod on a candidate node would push that domain’s skew above maxSkew, the constraint is unsatisfied for that node.
Two details trip people up. First, maxSkew: 1 does not mean “one pod per domain” — it means the busiest domain may hold at most one more pod than the emptiest. Six replicas over three zones with maxSkew: 1 gives 2/2/2. Seven replicas gives 3/2/2, which is still legal.
Second, the minimum is taken over domains that actually exist. If only two zones have schedulable nodes, the scheduler balances across two zones and never notices the third is gone. minDomains fixes that: set minDomains: 3 and when fewer than three eligible domains exist, the global minimum is treated as zero, which makes the skew large and blocks the placement. That is the field you want when “the third zone is down” must be a scheduling failure rather than a silent re-balance onto two zones.
What happens when the constraint cannot be met is whenUnsatisfiable:
DoNotSchedule makes the constraint a filter — no node passes, the pod stays Pending. ScheduleAnyway turns it into a scoring preference: the pod still gets placed, but the scheduler prefers nodes that reduce skew.
Why this beats podAntiAffinity. Anti-affinity with requiredDuringSchedulingIgnoredDuringExecution and topologyKey: kubernetes.io/hostname says “at most one of these pods per node.” It is binary. It cannot express “roughly even, two or three per node is fine,” so the moment replicas exceed nodes, every extra pod is unschedulable. The preferred variant is the opposite problem: it is a weighted hint with no ceiling on imbalance. Anti-affinity also gets expensive to evaluate — the scheduler compares the incoming pod against existing pods pairwise, which shows up as scheduling latency on large clusters. Topology spread expresses the actual intent, a bounded imbalance, and evaluates in one pass per domain.
Step-by-step
1. Confirm your nodes have zone labels. Everything below depends on this.
kubectl get nodes -L topology.kubernetes.io/zone
NAME STATUS ROLES AGE VERSION ZONE
node-01 Ready worker 41d v1.31.4 zone-a
node-02 Ready worker 41d v1.31.4 zone-a
node-03 Ready worker 41d v1.31.4 zone-b
node-04 Ready worker 41d v1.31.4 zone-b
node-05 Ready worker 41d v1.31.4 zone-c
node-06 Ready worker 41d v1.31.4 zone-c
An empty ZONE column means the constraint will never work. Label the nodes before going further:
kubectl label node node-05 topology.kubernetes.io/zone=zone-c
node/node-05 labeled
2. Write the Deployment with two constraints. A hard one across zones, a soft one across nodes. This is the shape we use for most stateless services.
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
namespace: storefront
spec:
replicas: 6
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
topologySpreadConstraints:
# Hard: no zone may hold more than one extra replica.
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: web
matchLabelKeys:
- pod-template-hash
# Soft: prefer to spread across nodes, but never block on it.
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: web
containers:
- name: web
image: registry.k8s.io/e2e-test-images/agnhost:2.45
args: ["netexec", "--http-port=8080"]
ports:
- containerPort: 8080
resources:
requests:
cpu: 100m
memory: 64Mi
matchLabelKeys: [pod-template-hash] is the field that makes rolling updates behave. Without it, the constraint counts old-ReplicaSet pods and new-ReplicaSet pods together, so during a rollout the scheduler sees a distribution that includes pods about to be deleted and refuses to place the new ones. With it, each ReplicaSet revision is spread independently.
3. Apply it.
kubectl apply -f web-deployment.yaml
deployment.apps/web created
4. Watch the pods reach Running. If the constraint is unsatisfiable, you will see it here rather than in production.
kubectl -n storefront rollout status deployment/web --timeout=120s
deployment "web" successfully rolled out
5. Add minDomains if a missing zone must be an error. Append it to the zone constraint:
- maxSkew: 1
minDomains: 3
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: web
minDomains is only valid together with whenUnsatisfiable: DoNotSchedule; the API server rejects it otherwise.
6. Set cluster-wide defaults, if you control the scheduler. Workloads that never declare a constraint get whatever the scheduler’s PodTopologySpread plugin is configured with. The built-in default is maxSkew: 3 on hostname and maxSkew: 5 on zone, both ScheduleAnyway. Tighten it in KubeSchedulerConfiguration:
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: default-scheduler
pluginConfig:
- name: PodTopologySpread
args:
defaultConstraints:
- maxSkew: 2
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
defaultingType: List
Keep cluster defaults on ScheduleAnyway. A cluster-wide DoNotSchedule will eventually block a pod that no one expected to be topology-aware, and the person debugging it will have no idea where the constraint came from.
Validate it works
Check where the pods actually landed:
kubectl -n storefront get pods -l app=web -o wide
NAME READY STATUS NODE NOMINATED NODE
web-6c8f4b7d9c-2xk4p 1/1 Running node-01 <none>
web-6c8f4b7d9c-4wq7z 1/1 Running node-03 <none>
web-6c8f4b7d9c-8mfjr 1/1 Running node-05 <none>
web-6c8f4b7d9c-h2ldv 1/1 Running node-02 <none>
web-6c8f4b7d9c-p9nbt 1/1 Running node-04 <none>
web-6c8f4b7d9c-vc3sq 1/1 Running node-06 <none>
Then count pods per zone rather than eyeballing node names:
kubectl -n storefront get pods -l app=web \
-o jsonpath='{range .items[*]}{.spec.nodeName}{"\n"}{end}' \
| xargs -I{} kubectl get node {} \
-o jsonpath='{.metadata.labels.topology\.kubernetes\.io/zone}{"\n"}' \
| sort | uniq -c
2 zone-a
2 zone-b
2 zone-c
Now prove it recovers. Drain a node and confirm the replacement pod does not pile into an already-busy zone:
kubectl drain node-01 --ignore-daemonsets --delete-emptydir-data
node/node-01 cordoned
evicting pod storefront/web-6c8f4b7d9c-2xk4p
pod/web-6c8f4b7d9c-2xk4p evicted
node/node-01 drained
Re-run the counting command. With node-02 still up in zone-a, you should see 2/2/2 again. Uncordon when you are done:
kubectl uncordon node-01
node/node-01 uncordoned
Pair this with a PodDisruptionBudget so the drain itself cannot evict a whole zone’s worth of pods at once — see Pod Disruption Budgets and the graceful node drain runbook.
Troubleshooting
Pods Pending with “didn’t match pod topology spread constraints”. Read the full FailedScheduling event; the counts tell you which rule bit.
kubectl -n storefront get events --field-selector reason=FailedScheduling
0/6 nodes are available: 4 node(s) didn't match pod topology spread constraints,
2 node(s) had untolerated taint {node.kubernetes.io/unreachable: }.
The usual cause is arithmetic, not a bug: you asked for maxSkew: 1 across three zones but only two zones have schedulable capacity, so any placement creates a skew of 2. Either restore capacity in the missing domain, raise maxSkew, or downgrade that constraint to ScheduleAnyway. A maxSkew: 1 hostname constraint on DoNotSchedule with more replicas than nodes is unsatisfiable by construction and will stay Pending indefinitely — nothing retries its way out of that.
Nodes missing topology.kubernetes.io/zone. A node without the topologyKey label is not part of any domain and is excluded from placement entirely for that constraint. Find them:
kubectl get nodes -l '!topology.kubernetes.io/zone'
NAME STATUS ROLES AGE VERSION
node-07 Ready worker 3h v1.31.4
This shows up after adding a node manually, or when a cloud-controller-manager has not finished labelling a fresh node. Label it and the pods schedule on the next attempt.
Spread is respected on scale-up and ignored on scale-down. Topology spread is a scheduling constraint. Nothing in the ReplicaSet controller consults it when choosing which pods to delete, so scaling from 6 to 4 can leave you at 3/1/0. Deleting the surplus pods yourself lets the scheduler re-place them correctly, or you can run the Descheduler’s RemovePodsViolatingTopologySpreadConstraint strategy on a schedule to correct drift.
Cluster Autoscaler will not add the node you expected. With DoNotSchedule, a Pending pod is the signal Cluster Autoscaler uses to grow the cluster — but it has to simulate which node group would help. If your node groups are not zone-scoped, or the autoscaler cannot tell which zone a new node would land in, it may scale a group that does not relieve the skew, or decline to scale at all. Use one node group per zone and enable --balance-similar-node-groups. Scale-down causes the mirror problem: the autoscaler removing the last node in a zone converts a healthy 2/2/2 into an unsatisfiable constraint.
A rolling update stalls halfway. Almost always the missing matchLabelKeys: [pod-template-hash]. The new ReplicaSet’s pods are counted alongside the old one’s, the combined distribution already exceeds maxSkew, and no new pod can be placed until old ones die — which they will not, because the rollout waits for the new ones. Adding matchLabelKeys breaks the deadlock. On clusters older than 1.27, use maxSurge: 0 on the Deployment strategy instead.
When this is the wrong approach
- Single-zone clusters. With one zone, a zone-level constraint is a no-op and a hostname-level one is often better served by resource requests and the default scoring. Spread constraints buy you nothing that the scheduler was not already doing.
- You need strict placement, not balance. “Exactly one pod per node, no exceptions” is what a DaemonSet is for. “This pod must never share a node with that pod” is genuinely
podAntiAffinity. Topology spread is for bounded imbalance, and forcing it into an exact-placement role produces the unsatisfiable-constraint trap. - Stateful workloads pinned to volumes. A pod bound to a zonal PersistentVolume can only schedule in that volume’s zone. The spread constraint and the volume topology will fight; solve placement at the StorageClass level with
volumeBindingMode: WaitForFirstConsumerand let the constraint apply to the pods, not to storage that cannot move. - Fewer than three domains. Two zones with
maxSkew: 1is workable but brittle — losing one zone leaves a single domain, and anyminDomainsyou set will block scheduling exactly when you most want the surviving zone to absorb traffic.
The authoritative reference is the Kubernetes documentation on Pod Topology Spread Constraints, alongside Assigning Pods to Nodes for how affinity and node selectors interact with the eligible-domain calculation.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.