Introduction

Topology spread constraints tell the Kubernetes scheduler how evenly replicas must sit across zones and nodes, and Pod priority preemption decides which Pods keep capacity when no node has room. Together they stop two quiet failures: replicas stacked in one failure domain, and batch work crowding out production traffic.

This is lesson 16 in the Kubernetes Roadmap series and the last placement lesson in Module 7. The previous lesson, Kubernetes Taints and Tolerations: Dedicated Nodes Without Chaos, covered keeping Pods off nodes they do not belong on. This lesson covers the opposite pressure: spreading Pods out, then ranking them when spreading is not enough. The next lesson opens Module 8 with Kubernetes Storage: PVC, StorageClass and CSI Provisioning.

Here is an illustrative composite scenario, built from a pattern platform teams recognise rather than one named incident. A checkout service runs six replicas with no placement rules. The scheduler packs four replicas into the zone with the most free capacity. A network fault isolates that zone, the service loses two thirds of its capacity in one minute, and the surviving replicas absorb triple traffic. In the same week, a reporting job with generous resource requests fills the remaining nodes, and a checkout rollout waits Pending because nobody ranked the workloads. Nothing crashed. The cluster did exactly what it was told, and nobody had told it that zones or importance mattered.

The 5-minute takeaway: give every multi-replica service a hard zone spread with maxSkew 1, add a soft hostname spread, and assign one of a few governed PriorityClasses. Spread decides where replicas may land. Priority decides who waits, who runs, and who gets evicted when capacity runs short. Both controls act at scheduling time, so verify placement after every rollout instead of assuming it holds.


1. How topology spread constraints count skew across domains

Topology spread constraints work by counting matching Pods in each topology domain, meaning each zone or node named by a node label, then comparing every domain with the least loaded one. A candidate node passes when placing the Pod there keeps that gap, called skew, at or below your maxSkew limit.

The count only includes Pods in the same namespace that match the constraint labelSelector, plus the incoming Pod when it matches that selector. Skew for a domain equals its matching Pod count minus the smallest matching count across all eligible domains. Eligible domains are built from nodes that exist and carry the topologyKey label, after node selector and affinity rules narrow the field. The scheduler repeats this arithmetic for every candidate node, which is why spread stays cheap even in large clusters: one pass over domains, not a comparison against every running Pod.

Work the numbers once and the behaviour stops surprising you. With three zones holding 2, 2 and 1 matching Pods, the minimum is 1. Placing the next Pod in a full zone gives skew 2, which breaks maxSkew 1, so those nodes fail. Placing it in the emptiest zone gives skew 1, which passes. Six replicas across three zones therefore settle at 2, 2 and 2, and seven replicas settle at 3, 2 and 2. maxSkew 1 never means one Pod per zone. It means the busiest domain may hold at most one more Pod than the emptiest.

Two limits matter in production. First, spread is evaluated only when a Pod is scheduled. Nothing moves a running Pod because the distribution later worsened, so scale-down, node loss and rollouts can all leave an uneven layout behind. Second, the scheduler ships soft default spread preferences for Pods with no constraints of their own, wide tolerances that exclude nothing. A Deployment with no explicit constraint can still stack every replica in one zone. Explicit constraints are how you turn a preference into a guarantee you can reason about during an incident.


2. Choosing topologyKey values for topology spread constraints

Topology spread constraints group nodes through topologyKey, a node label key whose value defines each domain. The zone label protects against availability zone loss, the hostname label protects against single node loss, and the region label suits rare multi-region designs. Pick the domain that matches the failure you actually fear.

Cloud node pools normally stamp three well-known labels: topology.kubernetes.io/zone, topology.kubernetes.io/region and kubernetes.io/hostname. Verify them before writing any constraint, because a constraint over a label your nodes lack protects nothing. Nodes missing the topologyKey label do not form a domain for that constraint, and Pods carrying the constraint are not placed on them. A cluster where one node pool forgot zone labels can quietly shrink your spread to the labelled subset.

Match the key to the blast radius. A zone constraint survives the loss of a whole availability zone, which is the failure that takes services down in cloud regions. A hostname constraint survives node drains, node failures and noisy neighbours on one machine. Most production services want both, layered: hard on zone, soft on hostname. A region constraint only helps when one cluster genuinely spans regions, which is uncommon, and custom keys such as a rack or failure-domain label suit bare-metal fleets where the rack is the unit that fails.

Check replica counts against domain counts before blaming the scheduler. Three replicas across three zones gives one Pod per zone and no headroom when a zone degrades. Six replicas gives two per zone, so losing one zone still leaves four Pods serving. Spread cannot invent capacity. If your availability target needs the service to survive a zone loss at full traffic, replica count, resource requests and autoscaling headroom must agree with the spread rule, not fight it.

bash
kubectl get nodes -L topology.kubernetes.io/zone,kubernetes.io/hostname
kubectl get pods -l app=checkout -o wide

3. maxSkew and whenUnsatisfiable in topology spread constraints

Topology spread constraints expose two decisions that shape every outcome: maxSkew sets the largest allowed gap between the fullest and emptiest domains, and whenUnsatisfiable decides whether a Pod waits or runs anyway. DoNotSchedule holds the Pod Pending, while ScheduleAnyway still places it and merely prefers nodes that reduce skew.

maxSkew must be at least 1, and you should set it explicitly rather than rely on defaults. maxSkew 1 gives the tightest evenness and the most Pending risk when a domain lacks capacity. maxSkew 2 tolerates a wider gap, which suits large replica counts where perfect balance matters less than keeping Pods running. The right value follows the failure maths: with maxSkew 2 across three zones, a 4, 2 and 2 layout is legal, and losing the busy zone costs half your capacity instead of a third.

DoNotSchedule turns the constraint into a filter. No node passes, the Pod stays Pending, and that Pending Pod becomes a visible signal for operators and autoscalers. ScheduleAnyway turns the constraint into a score. The Pod still runs, nodes that reduce skew rank higher, and nothing warns you when capacity pressure overrides the preference. Neither setting is safer in the abstract. DoNotSchedule trades availability now for balance guarantees. ScheduleAnyway trades balance guarantees for availability now. Critical services usually take the hard zone rule and accept Pending during a zone outage, because running unbalanced is exactly the state that fails the next fault.

Two newer fields close common gaps, so check support with kubectl explain on your cluster. minDomains, stable since Kubernetes 1.30, works with DoNotSchedule: when fewer eligible domains exist than the value you set, the minimum count is treated as zero, which stops a cold start from stacking every replica in the first zone that gains a node. matchLabelKeys, beta and enabled by default since 1.27, adds label values from the incoming Pod to the selector. Setting it to pod-template-hash makes a Deployment count old and new ReplicaSets separately during rollouts, instead of letting the outgoing Pods distort the skew maths.


4. Writing topology spread constraints in a Deployment

Topology spread constraints live in the Pod spec, so a Deployment carries them under its template spec alongside containers and priorityClassName. One hard zone constraint plus one soft hostname constraint covers most services. The labelSelector must match the Pod labels, or the scheduler counts the wrong Pods and the rule quietly weakens.

The manifest below spreads six checkout replicas across zones with a hard rule, keeps them off shared nodes where possible with a soft rule, and assigns a production PriorityClass that the priority sections define. Resource requests are included on purpose: spread and preemption both reason about requests, and Pods without requests give the scheduler nothing honest to plan with.

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: checkout
  labels:
    app: checkout
spec:
  replicas: 6
  selector:
    matchLabels:
      app: checkout
  template:
    metadata:
      labels:
        app: checkout
    spec:
      priorityClassName: production
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: topology.kubernetes.io/zone
          whenUnsatisfiable: DoNotSchedule
          minDomains: 3
          labelSelector:
            matchLabels:
              app: checkout
          matchLabelKeys:
            - pod-template-hash
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: ScheduleAnyway
          labelSelector:
            matchLabels:
              app: checkout
      containers:
        - name: checkout
          image: checkout:1.4.2
          ports:
            - containerPort: 8080
          resources:
            requests:
              cpu: 250m
              memory: 256Mi
            limits:
              cpu: 500m
              memory: 512Mi

Read the selector lines twice. The labelSelector decides which Pods count toward the spread, and it must match the labels on the Pods the constraint belongs to. When the selector misses the Pod's own labels, the incoming Pod never adds to any count, every replica looks like the first one, and the constraint becomes decoration. Keep the selector narrow and stable: app-level labels that survive rollouts, plus matchLabelKeys for the template hash when rollout behaviour matters.

Multiple hard constraints combine as a logical AND. A node must satisfy every DoNotSchedule constraint before the Pod can land, so stacking hard rules on zone, hostname and a custom key multiplies Pending risk fast. Layer deliberately: hard where the failure demands it, soft everywhere else. After applying, verify with kubectl get pods -o wide and count Pods per zone yourself. The scheduler reports success per Pod, not per distribution, so the distribution check belongs to you and to your deployment pipeline.


5. Topology spread constraints versus Pod anti-affinity

Topology spread constraints ask one global question about replica counts, while Pod anti-affinity asks a pairwise question about neighbouring Pods. Spread fits replicas of one workload that must stay even across domains. Anti-affinity fits avoidance rules against a different workload, such as keeping database Pods away from batch Pods on shared nodes.

Required anti-affinity is binary. With topologyKey set to zone, it forbids a second matching Pod in any zone that already holds one, so a three-zone cluster caps the workload at three replicas and the fourth Pod stays Pending. With hostname it caps replicas at the node count. Preferred anti-affinity removes the cap but also removes the guarantee, because the rule becomes one score among many and loses silently when the cluster gets tight. Spread expresses the real intent, a bounded imbalance, and keeps working as replica counts grow past the domain count.

Question Topology spread constraints Pod anti-affinity
Core question How uneven are replica counts across domains? Does this domain already hold a matching Pod?
Guarantee shape Bounded gap through maxSkew Forbidden co-location, or a soft preference
Replicas beyond domain count Allowed, counts stay even Required form blocks them with Pending Pods
Avoiding a different workload Not supported, counts one matching set Supported through any label selector
Scheduling cost One pass over domains Checked against matching Pods per node
Best fit Even replicas across zones and nodes Hard separation between unlike workloads

Keep anti-affinity for separation between unlike workloads. "Never place a database replica on a node running batch jobs" names a different Pod set, and spread constraints cannot express it because they only balance Pods matching their own selector. The scheduling lesson, Kubernetes Scheduling: nodeSelector, Affinity and Anti-Affinity, covers affinity syntax in depth. Use spread for replica evenness, anti-affinity for avoidance, and expect both to act only at scheduling time. Neither mechanism rebalances running Pods when the world changes underneath them.


6. PriorityClass basics beside topology spread constraints

Topology spread constraints control placement, while a PriorityClass assigns each Pod an integer priority that orders the scheduling queue and enables preemption. PriorityClasses are cluster-scoped objects, higher values win, and Pods without a class run at priority zero unless one class is marked as the global default for the whole cluster.

A PriorityClass maps a name to a value. User classes accept values from -2147483648 to 1000000000, names cannot start with system-, and the two built-in classes, system-cluster-critical and system-node-critical, sit near 2000000000 for platform components. Never assign system classes to application workloads. One class may set globalDefault true, and then every Pod without priorityClassName inherits it instead of zero. Pods reference a class through priorityClassName in the Pod spec, and the scheduler copies the value onto the Pod as its priority.

yaml
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
  name: production
value: 10000
globalDefault: false
preemptionPolicy: PreemptLowerPriority
description: "Production traffic. May preempt standard and batch Pods."
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
  name: standard
value: 1000
globalDefault: true
preemptionPolicy: PreemptLowerPriority
description: "Default tier for ordinary services."
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
  name: batch
value: -100
globalDefault: false
preemptionPolicy: Never
description: "Preemptible batch work. Never evicts other Pods."

The preemptionPolicy field decides whether Pods of a class may evict others. PreemptLowerPriority is the default and allows preemption. Never, stable since Kubernetes 1.24, keeps the queue advantage of a high value while forbidding eviction: the Pod waits for free capacity instead of taking it. Read that field carefully, because it controls only whether a Pod preempts others. A Pod in a Never class can still be preempted by a higher priority Pod. Priority also feeds kubelet eviction ranking under node pressure, a separate mechanism from scheduler preemption that the Kubernetes OOMKilled troubleshooting guide covers from the memory side.


7. How preemption interacts with topology spread constraints

DoNotSchedule topology spread constraints stay hard filters during preemption, so evicting lower priority Pods only helps when their removal makes the pending Pod schedulable on that node. The scheduler searches node by node for a victim set that frees enough room, prefers victims with lower priority, then sets a nominated node and waits.

Preemption starts when a Pod cannot schedule anywhere and its class allows preemption. The scheduler examines each node and asks whether removing one or more lower priority Pods would make the pending Pod pass every filter on that node: resources, taints and tolerations, affinity, volume placement and hard spread rules. Victim selection favours the smallest useful set, lowest priorities first, and victims whose PodDisruptionBudgets would survive. The scheduler then marks the chosen node through nominatedNodeName, deletes the victims with their normal graceful termination period, and schedules the pending Pod once the room is real. Victim controllers recreate their Pods elsewhere, where those Pods may preempt still lower priority work or wait Pending.

The interaction with spread cuts both ways. Preemption cannot fix a Pod blocked by a taint it does not tolerate, a volume pinned to another zone, or a quota with no room, because evicting neighbours changes none of those facts. A Pod blocked purely by skew is also a poor preemption candidate: eviction frees resources, not domain balance, and the scheduler only preempts when the victim set makes the Pod schedulable. Design accordingly. When a critical service must run during a zone outage, a hard zone spread will hold its new Pods Pending no matter how high the priority value climbs. That tension is a policy choice, not a bug: balance guarantee or immediate capacity, decided in advance through whenUnsatisfiable and the priority tier.

Watch preemption through events rather than guesswork. A Preempted event names the victim and the Pod that displaced it, and kubectl describe on the pending Pod shows the nominated node while victims terminate. Repeated preemption of the same workload signals a capacity or tiering problem, not scheduler misbehaviour. Treat a rising preemption rate as an alertable symptom, the same way you treat restarts.

bash
kubectl get events --all-namespaces --field-selector reason=Preempted
kubectl get priorityclass
kubectl describe pod checkout-7d9f8c6b5-abcde

8. Topology spread constraints, PodDisruptionBudgets and preemption

Topology spread constraints place replicas apart before trouble starts, while a PodDisruptionBudget limits how many Pods voluntary disruptions may take down at once. During preemption the scheduler treats budgets as best effort only. It prefers victims whose budgets survive, then preempts anyway when no clean victim set exists on any node.

A PodDisruptionBudget guards the eviction API, which is the path node drains and voluntary disruptions use. When disruptionsAllowed reaches zero, the eviction API refuses and the drain waits. Scheduler preemption does not travel that path. The scheduler consults budgets while choosing victims and tries to pick Pods whose removal keeps every budget intact, but the documentation is explicit that respect is best effort, not guaranteed. If the only way to place a higher priority Pod violates a budget, the budget loses. Plan capacity and tiers with that sentence in mind, because a budget is a drain guard, not a preemption shield.

yaml
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: checkout
spec:
  minAvailable: 4
  selector:
    matchLabels:
      app: checkout

Spread and budgets reinforce each other when both are honest. Spread keeps replicas in separate domains so one drain or zone fault touches a minority of Pods. The budget then limits voluntary churn to what the service can absorb, and preemption remains the rare path reserved for genuinely higher priority work. The Deployment Reliability and Canary Releases guide covers the rollout side of the same discipline. Keep budgets satisfiable: minAvailable equal to the replica count blocks every drain forever, and a budget over a single replica is a promise the cluster cannot keep during upgrades.


9. Topology spread constraints with Cluster Autoscaler and Karpenter

Topology spread constraints turn placement rules into Pending Pods, and Pending Pods are the signal Cluster Autoscaler and Karpenter use to add nodes. Neither tool can rescue a constraint that no possible node satisfies. Zone capacity, taints, quotas and pool limits still decide whether scale-up can ever make the Pod schedulable.

The scheduler only knows domains from nodes that already exist. That fact drives the cold-start trap: scale a service from zero in a cluster with nodes in one zone, use ScheduleAnyway on the zone key, and every replica can land in that zone before nodes elsewhere become Ready. DoNotSchedule with minDomains set to your zone count holds the extra Pods Pending instead, and Pending Pods are what autoscalers watch. Cluster Autoscaler simulates scheduling against its node groups and adds a node from a group that could satisfy the Pod. Karpenter reads pending Pods and provisions a node shaped and placed for them. The mechanics differ, and the Karpenter vs Cluster Autoscaler comparison owns that detail. The shared rule is simple: a Pending Pod whose constraints no hypothetical node satisfies will wait forever, and the autoscaler log will say why.

Priority changes the order of events. A high priority Pod with PreemptLowerPriority may evict batch Pods on existing nodes before any new node arrives, which is fast and disruptive. The same Pod in a Never class waits, giving the autoscaler time to add capacity instead. Choose per workload: latency-critical production Pods often preempt, while large batch or training jobs usually wait for fresh nodes. Also remember scale-down. Autoscalers remove underused nodes, spread is not rechecked for running Pods, and a service can drift unbalanced across zones after consolidation. Recheck distribution after node churn the same way you recheck it after rollouts.


10. Priority tiers that respect topology spread constraints

Topology spread constraints work best with a small set of priority tiers that every team can explain without a meeting. Keep one narrow tier for platform-critical services, one for production traffic, one standard tier, and one preemptible tier for batch work. Priority inflation destroys the signal, because universal urgency protects nothing at all.

Tier Example value preemptionPolicy Fits
Platform critical 100000 PreemptLowerPriority Ingress, DNS, admission webhooks, core operators
Production 10000 PreemptLowerPriority Customer-facing services with availability targets
Standard 1000 PreemptLowerPriority Internal services, default through globalDefault
Batch -100 Never Jobs, reports, backfills that can restart safely

Govern the tiers like an API. Restrict who may create PriorityClasses and who may reference the top tiers, because an untrusted user who can claim the highest value can evict production work. Review tier assignments during service reviews, and keep the top tier small enough that its Pods could all schedule on the surviving zones during an outage. A top tier that only fits when every zone is healthy is a fiction.

Pair tiers with spread honestly. A production service with a hard zone spread and a high tier will still wait during a zone outage when balance cannot be met. If the business answer is "run degraded in the surviving zones", use ScheduleAnyway on the zone key or a wider maxSkew, and write that choice down. If the answer is "never run unbalanced", keep DoNotSchedule and size replicas so the surviving domains carry the load. Either answer is defensible. An accidental answer discovered during an incident is not.


11. Troubleshooting topology spread constraints and preemption

Topology spread constraints fail in readable ways once you check domains, selectors and events in order. Start with node labels, count matching Pods per domain, then read the FailedScheduling message on the pending Pod. For preemption surprises, check PriorityClass values, Preempted events and budget status before changing any YAML in the cluster.

Symptom Likely cause First check
Pod Pending, message names topology spread Skew limit reached, or a domain has no eligible node Count matching Pods per zone, then read node labels
All replicas in one zone despite a constraint labelSelector does not match the Pod labels Compare selector labels with template labels
Constraint ignored on some nodes Nodes lack the topologyKey label List nodes with zone and hostname labels
Pod Pending during a zone outage DoNotSchedule with maxSkew 1 and one zone down Decide balance guarantee versus degraded running
High priority Pod still Pending No victim set makes it schedulable, or policy Never Read FailedScheduling detail and the class policy
Pods evicted despite a budget Preemption respects budgets best effort only Check Preempted events and tier assignments
Autoscaler adds no node No group or pool can satisfy zone, taints or quota Read autoscaler logs for the pending Pod
Distribution uneven after rollout Spread applies at scheduling time only Recount Pods per domain, check matchLabelKeys

Work the matrix top to bottom with evidence. kubectl describe pod prints the scheduler's own reasons, and those reasons name the failing filter in plain language. Count Pods per domain with kubectl get pods -o wide before touching maxSkew, because half of all spread incidents are label or selector mistakes wearing a scheduling costume. For preemption, identify the displacing Pod from the Preempted event, compare priority values, and only then discuss tier changes. Changing values before reading events trades one surprise for another.


12. Final checklist for topology spread constraints and priority

Topology spread constraints and Pod priority are finished when replicas survive a zone loss on paper, priority tiers stay few and governed, and Pending Pods produce a clear autoscaler signal. Run the checklist against one production service first, watch a rollout and a node drain, then roll the pattern out service by service.

  • Node zone and hostname labels verified on every node pool before constraints ship.
  • Hard zone spread with maxSkew 1 and minDomains set to the zone count.
  • Soft hostname spread added where node-level separation matters.
  • labelSelector matches Pod labels, with matchLabelKeys covering pod-template-hash.
  • Replica count sized so surviving zones carry traffic after one zone loss.
  • Priority tiers limited to a governed set, with batch work preemptible.
  • PodDisruptionBudget satisfiable, with minAvailable below the replica count.
  • Pending Pod behaviour tested against the autoscaler in a staging cluster.
  • Distribution recounted after rollouts, drains and autoscaler consolidation.

Placement and priority are capacity policy written in YAML. Review them with the same care as resource requests, because during an incident they decide which Pods exist at all. Start with one service, prove the zone-loss maths on paper, watch the scheduler honour it in staging, and then make the pattern the default for every multi-replica workload you own.

Frequently Asked Questions

What do topology spread constraints do in Kubernetes?

Topology spread constraints tell the scheduler how evenly Pods matching a label selector must sit across topology domains such as zones and nodes. Each constraint sets maxSkew, topologyKey and whenUnsatisfiable. The scheduler counts matching Pods per domain and only places a Pod where the resulting gap stays within the limit you set.

How does maxSkew work in topology spread constraints?

maxSkew is the largest allowed difference between the fullest domain and the emptiest eligible domain. Skew for a domain equals its matching Pod count minus the smallest matching count anywhere. With maxSkew 1 across three zones, six replicas settle at 2, 2 and 2, while seven settle at 3, 2 and 2.

Should topology spread constraints use DoNotSchedule or ScheduleAnyway?

Use DoNotSchedule when balance is a hard availability requirement, accepting that Pods stay Pending when a domain lacks capacity. Use ScheduleAnyway when running degraded beats waiting, accepting that placement becomes a preference the scheduler may override. A common pattern pairs a hard zone constraint with a soft hostname constraint.

How do topology spread constraints differ from Pod anti-affinity?

Topology spread constraints balance replica counts across domains with a bounded gap, so replicas may outnumber domains. Pod anti-affinity forbids or discourages co-location with matching Pods, which suits separation between different workloads. Required anti-affinity on zone caps replicas at the zone count, while spread keeps working as replicas grow.

Why do topology spread constraints leave a Pod Pending?

A Pod stays Pending when no node passes every hard filter, and a DoNotSchedule spread rule is one of those filters. Common causes are a zone with no eligible nodes, skew already at the limit, missing topology labels, or taints that shrink the eligible domains. The FailedScheduling event on the Pod names the failing reason.

How does Pod priority preemption choose which Pods to evict?

The scheduler looks for a node where removing lower priority Pods makes the pending Pod schedulable under every filter. It prefers small victim sets with the lowest priorities and tries to spare Pods whose PodDisruptionBudgets would break. Victims then terminate gracefully while the pending Pod waits on its nominated node.

Do topology spread constraints rebalance Pods after scale-down or node loss?

No. Topology spread constraints are evaluated only when a Pod is scheduled, and running Pods never move because the distribution worsened later. Scale-down, node loss and rollouts can all leave an uneven layout behind. Recount Pods per domain after churn, and use a descheduler or controlled rollouts when rebalancing matters.

⚡ KUBERNETES SCENARIO INTERVIEW PREP

Preparing for Senior Platform & SRE Interviews

Practice real-world cluster triage, RBAC debugging, and pod scheduling scenarios in our Kubernetes scenario interview questions hub.

Explore Interview Scenarios →