Spreading pods across zones and nodes with topology spread constraints

Topology spread constraints and anti-affinity decide where Kubernetes places replicas so one node or zone failure does not remove the whole service. This page covers the options, setup, autoscaling interaction and what to confirm in your environment.

On this page

Why topology spread constraints matter for topology spread constraints on zones and nodes

A service with five replicas can still be fully down if all five pods landed on one node or in one availability zone. When that node or zone fails, the scheduler has nothing left to fall back on, and every replica goes down together. Topology spread constraints are the Kubernetes mechanism for telling the scheduler how evenly pods of a workload should be distributed across failure domains such as nodes and zones, so a single domain failure removes only a fraction of capacity. They are configured in the topologySpreadConstraints field of a pod spec, and the scheduler counts matching pods per topology domain, using the topologyKey label (for example topology.kubernetes.io/zone) to define each domain.

Teams need these constraints when a workload has more than one replica and the default scheduling behavior would concentrate them. The default scheduler does not treat spreading as a goal unless you declare it, and a cluster that looks balanced at install time can drift as nodes are added, drained or replaced. The Kubernetes scheduling documentation describes the model: each constraint sets a maxSkew, which is the allowed difference in matching pod counts between the most and least loaded domains. The decision you make is how strict to be, expressed through whenUnsatisfiable, since a hard requirement can leave pods pending while a soft preference only steers placement. Confirm the exact field behavior for your Kubernetes version against the current scheduling documentation before you standardize a template.

Pod anti-affinity also keeps replicas apart, but its purpose is narrower. Anti-affinity expresses a rule about whether a pod may share a domain with other pods that match a selector, which is useful for keeping a specific pair of workloads apart. Topology spread constraints express an even distribution across all domains of a given key, which is what you want when the goal is zone resilience for one service. Many platform teams use both: spread constraints for the even layout, and anti-affinity for specific separations. Whichever you choose, plan the failure you are designing for, then test it with a drain of one node and, where your topology allows, one zone, before you rely on the setting in production.

Which topology spread settings fit which failure goal

This table maps each topology spread constraint field, plus anti-affinity, to the placement goal it serves and the trade-off it carries. Read each row against the Kubernetes minor version in your cluster, because optional fields depend on release. The main takeaway is that whenUnsatisfiable and labelSelector decide most outcomes, while the optional fields refine behavior once those are right.

Field or optionWhat it controlsWhen it fitsWhat to confirm
topologyKeyThe node label that defines a domain, such as the zone or hostname labelChoose the zone label to spread across zones, or the hostname label to spread across nodesConfirm that nodes carry the label you choose, and that the label is set consistently by your provisioning tooling
maxSkewThe maximum allowed difference in matching pod count between the most and least loaded domainsA low value such as 1 for even spread; a higher value tolerates uneven placement when capacity is unevenConfirm the value against the number of domains and replicas, since a small replica count cannot spread evenly across many domains
whenUnsatisfiable: DoNotScheduleBlocks scheduling of a pod that would violate maxSkewHard placement rules where an uneven zone is worse than a Pending podConfirm that autoscaling or spare capacity exists in every domain, or pods can stay Pending during scale-out or node loss
whenUnsatisfiable: ScheduleAnywayPrefers spread but still schedules the pod when the constraint cannot be metServices that must keep running during a zone outage even if placement becomes unevenConfirm monitoring will show skewed placement, because the scheduler does not block it
labelSelectorWhich existing pods count toward the skew calculationAlways required in practice; scope it to the workload's own labels so unrelated pods do not distort the countConfirm the selector matches the pod template labels of the Deployment, StatefulSet or other controller
minDomainsThe minimum number of eligible domains the scheduler should see before treating spread as satisfiedEnsures replicas reach several zones rather than piling into the first one or two availableConfirm availability for your Kubernetes minor version and that enough domains exist before enforcing it
matchLabelKeysLabel keys whose values are added to the selector, so each revision of a workload spreads separately during rolloutsRolling updates where new and old ReplicaSets should each stay balancedConfirm availability for your Kubernetes minor version and test rollout behavior before relying on it
nodeAffinityPolicyWhether node affinity and selectors on the pod narrow the set of nodes counted for skewPods restricted to a subset of nodes, such as a GPU or dedicated pool, where unrelated nodes would skew the resultConfirm the default behavior and availability for your Kubernetes minor version
nodeTaintsPolicyWhether tainted nodes that the pod cannot tolerate are included in skew calculationClusters with tainted control-plane or dedicated nodes that would otherwise make a domain look permanently emptyConfirm the default behavior and availability for your Kubernetes minor version
Pod anti-affinity (required)Forbids two matching pods on the same topology domain, strictly one per domain when used with a zone or hostname keyStrict isolation of replicas, such as one database member per nodeScheduling cost: pods beyond the number of domains stay Pending, so size the domain count and autoscaling before use
Pod anti-affinity (preferred)Weights a preference against co-location without blocking schedulingSofter isolation where some co-location is acceptable during failuresConfirm the weight and topology key; the scheduler may still co-locate replicas under pressure

Choosing a spread pattern by service and failure goal

A stateless service that must keep serving when an entire zone goes dark needs its replicas distributed across zones as the primary goal. The spread constraint keys on the zone topology label, and the question is how strictly the scheduler must enforce that distribution. A soft rule lets the scheduler place pods wherever capacity exists and still prefers balance, which keeps the service running during a partial capacity event. A hard rule guarantees the spread but can leave pods pending when one zone lacks room, so the service may run at reduced count instead of failing over cleanly.

  • Zone label quality: confirm every node carries a consistent zone label, since missing labels make the constraint ineffective or unschedulable.
  • Capacity per zone: check whether each zone can absorb the pods that would move there during a loss of a neighbor.
  • Autoscaler behavior: confirm the node group or pool scales in each zone, because a hard rule waits on capacity that may not exist yet.
  • Storage affinity: if the workload mounts zonal volumes, the zone spread and the volume location can conflict.
  • Recovery expectation: decide whether reduced replica count during an outage is acceptable or whether pending pods are worse.

Before choosing this pattern, confirm which zones your cluster spans and whether the stateless workload has no zonal dependencies that would override the spread.

How the scheduler counts matching pods per domain

The scheduler decides whether a pod can land in a zone or on a node by counting how many matching pods already sit in each topology domain and comparing those counts. A topology domain is simply a set of nodes that share the same value for a node label named in the constraint's topologyKey, such as topology.kubernetes.io/zone for zones or kubernetes.io/hostname for individual nodes. Every distinct label value becomes one domain. For each candidate placement, the scheduler works out the skew, which is the difference between the most populated domain and the least populated domain, and compares it against the maxSkew you set. Before relying on this, confirm that every node carries the zone label your constraint uses, because a node without the key is not placed into any domain for that constraint.

Counting depends entirely on the labels being accurate and consistent. A node labeled with one zone name in one place and a slightly different spelling elsewhere creates a phantom domain with few or no pods, which pushes the scheduler to pile replicas into the other domains and makes the spread look correct on paper while it is not. Node labels set by a cloud provider, a bare-metal provisioning tool or a manual process can disagree, so audit them with kubectl get nodes -L topology.kubernetes.io/zone and check that new nodes from your autoscaler or machine templates receive the same labels before they join the cluster.

The count is also narrow. The constraint only sees pods whose labels match its labelSelector, and it only counts pods in the same namespace as the pod being scheduled. A Deployment that uses a selector covering only some of its pods, or a second workload that serves the same traffic under different labels, is invisible to the calculation, so the spread you designed is not the spread you get. Pods that are still terminating and pods waiting for a node also shape the result, so test the rule with a real rollout and inspect where replicas actually land rather than assuming the arithmetic from the manifest.

How a pending pod moves through spread and autoscaling decisions

The walk starts when the scheduler picks up a new replica that is still unbound. It checks the pod's topology spread constraints against the current pod counts in each zone or node domain. If a node satisfies every hard constraint, the pod binds; if a soft constraint can only be scored, the pod still binds to the best available node. If a hard constraint cannot be met, the pod stays Pending, and the cluster autoscaler may add nodes in a node group whose zone matches the gap. Check whether that node group actually exists in the needed zone, since a missing group leaves the pod pending.

Scheduler decision path for a spread-constrained replica, including the autoscaler branch.

How to configure topology spread constraints in a self-managed cluster

This sequence confirms node topology labels, maps capacity per zone, applies spread constraints to one workload on a non-production replica set, and proves with drain tests and recorded evidence that a node or zone loss leaves the service running.

  1. Confirm zone and hostname labels on every node

    List the node labels for every node in the cluster and confirm that each node carries a zone label and a hostname label with consistent values. Use the well-known topology label keys for zone and hostname, and check that no node is missing them or uses a second, conflicting key for the same zone. Ask your platform team who sets these labels (the cloud provider, the bootstrap tooling or a manual process), because labels added by hand often drift after node replacement. The step is done when a label query returns a value for every node and the zone values match your physical or cloud layout. Save the output as the baseline for the change record.

  2. Inventory node groups and capacity per zone

    Group the nodes by zone and by node pool, and record how many schedulable nodes and how much allocatable CPU and memory each zone holds. Note taints, cordoned nodes and any nodes reserved for system or GPU workloads, since those change how many domains a spread rule can actually use. Check whether each zone has enough capacity to run its share of replicas, because an unbalanced zone can make a constraint unsatisfiable. The step is done when you have a written table of zone, node, pool, taints and allocatable capacity that another engineer can reproduce.

  3. Choose the workload selector and topology keys

    Pick one non-production workload, such as a stateless Deployment with several replicas, and define the label selector that identifies its pods. Decide which topology keys to use: the zone key for zone spread and the hostname key for node spread. Confirm that the pod labels used in the selector are unique to this workload so the rule does not count pods from other services. Write down the chosen keys and selector in the change record. The step is done when a dry-run apply of the manifest is accepted and the selector matches only the intended pods.

  4. Set maxSkew and whenUnsatisfiable on a staging replica set

    Add the topologySpreadConstraints block to the pod template of the chosen workload in a non-production namespace. Set maxSkew, the allowed difference in matching pod counts between domains, and choose whenUnsatisfiable: DoNotSchedule to block placement that breaks the rule or ScheduleAnyway to prefer it without blocking. Explain the trade-off in the change record: a hard rule can leave pods Pending during zone loss or scaling, while a soft rule can concentrate pods silently. Confirm the API server accepts the manifest and that the Deployment rolls out. The step is done when the pods are Running and the rollout status reports success.

  5. Verify placement with pod-to-node mapping

    Run kubectl get pods with wide output filtered by the workload label, and join the pod names to their node names. Then get the zone label of each node so you can count pods per zone and per node. Compare the counts with the maxSkew you set and confirm that the spread matches the rule. If a pod is Pending, read its events with kubectl describe to see which constraint blocked it. The step is done when the mapping table shows the expected distribution and you have saved the command output with the timestamp and cluster name.

  6. Drain one node and observe rescheduling

    In a staging cluster only, cordon and drain one node that hosts pods of the workload, using the same drain procedure your operations team uses for maintenance. Watch whether replacement pods land on other nodes while still meeting the spread rule, and whether any pod stays Pending. Record how long the service endpoints were reduced and whether any pod entered a Pending state. Uncordon the node afterward and confirm it returns to the schedulable pool. The step is done when the drain result, pod events and endpoint count are captured in the test log.

  7. Drain a full zone and record results for review

    In the same staging cluster, drain all nodes in one zone in a controlled order and confirm which replicas survive, which move, and whether the remaining zones have room for the rescheduled pods. Check that the service still responds and that a hard rule did not leave pods Pending without a plan. Then restore the nodes and confirm the workload rebalances as expected. Store the test plan, command output, pod mapping before and after, events and the decision on whenUnsatisfiable in the change or audit record, along with the names of the people who approved the test. The step is done when the record shows the zone loss outcome and any follow-up changes are logged for production.

How autoscaling changes whether spread rules hold

A hard constraint with whenUnsatisfiable: DoNotSchedule holds only while the cluster can place a pod in every domain it names. If a zone has no node with spare capacity and the autoscaler has no node group that can add one there, the pod stays Pending. Scale-up is also not guaranteed to be even. When node groups are uneven in size, instance type or availability, the autoscaler may add capacity to only one zone to satisfy the pending pod, and the constraint then pushes replicas toward the zones that already have room. Confirm how your autoscaler chooses among node groups for balancing, including any balance-similar-node-groups setting, in the documentation for your autoscaler and distribution rather than assuming it spreads evenly.

A soft constraint, whenUnsatisfiable: ScheduleAnyway, avoids pending pods but can quietly concentrate replicas. The scheduler accepts a placement that violates maxSkew whenever it cannot find a better one, and nothing alerts you when that happens. Check actual placement after scale events, not only the manifest. Zonal storage adds a second constraint: a PersistentVolume provisioned in one zone pins its pod there, so a spread rule across zones can never be satisfied for that workload during a zone failure. Pod disruption budgets interact too. A budget that requires most replicas to stay available can block a drain on the node that holds the last replica in a sparse zone, so review budgets together with spread rules before maintenance. Test scale-up and drain behavior in a non-production cluster with the same node groups.

Security and operational risks of relying on node labels for placement

Topology spread constraints trust node labels to define failure domains, so the label set becomes part of your security and operations boundary. The cards below cover who can change those labels, who owns them, how drift goes unnoticed and how spread rules are reviewed.

Restrict who can patch node labels

Any identity that can change node labels can change how the scheduler groups nodes into zones or racks, and so change where replicas land. Review which roles hold patch or update rights on nodes, and remove them from broad groups or CI service accounts that do not need them. Check your RBAC bindings for wildcard verbs on the nodes resource, since a permission granted for a different purpose can reach node objects silently. Confirm this with a periodic access review rather than assuming the initial setup still holds.

Authentication docs

Audit every label change

A label edit on a node leaves no trace in the workload, so spread behavior can change without any deployment event. Confirm that your API server audit policy records create, update and patch requests on nodes, and that those records reach a store your security team reviews. Ask who is alerted when a zone label changes on a live node. Treat an unexplained change to a failure-domain label as a potential incident until someone has explained it.

Give automated labels an owner

Labels applied by cloud controllers, node provisioning tools or bootstrap scripts are often treated as facts, yet each one was set by a process that someone must maintain. Record which tool sets each topology label, which team owns that tool, and what happens when it is upgraded or replaced. If a node pool is rebuilt with a different label template, spread rules may keep running while the domains they expect no longer exist.

Watch for silent label drift

A node that joins with a missing or misspelled zone label can be accepted without error, and the scheduler then treats its pods as a separate domain or ignores the constraint for it. Over time, label sets across node pools diverge, and a spread rule that once covered three zones may cover fewer. Compare label sets across all nodes on a schedule, for example with a query on the standard zone and region labels, and flag any node that lacks them.

Alert on pending and uneven placement

When a constraint with whenUnsatisfiable set to DoNotSchedule cannot be met, replicas stay Pending instead of failing loudly, which can go unnoticed during a scale-out or a zone outage. Alert on Pending pods older than an agreed threshold and on replica counts that cluster in one domain. Set the threshold with your operations team, because scaling events legitimately create short Pending periods. Confirm that alerts reach an on-call rotation and not only a dashboard.

Review spread rules as code

A change to maxSkew, topologyKey or whenUnsatisfiable can shift capacity or block scheduling across a whole service, so it deserves the same review as any other workload manifest. Store spread rules in the same Git repository and pull request flow as Deployments, require approval from the service owner and the platform team, and run policy checks for required keys. Ask whether a rule change can be rolled back quickly and whether the rollout was tested in a non-production cluster first.

What teams ask before hiring help with zone and node spreading

What drives the cost of spreading pods across zones and nodes?

The cost depends on how much of the cluster is in scope, how many services need spread rules, and how the cluster is laid out. A cluster with three zones, a few stateless services and a single node pool is a smaller job than one with many teams, stateful workloads and several autoscaled pools. Storage design matters because zonal volumes can pin a pod to one zone, which changes which spread rules are possible. Autoscaler setup adds work when node groups differ by zone. Ask for a written scope that lists the services, zones, node pools and autoscaler in use, since that list is what the quote follows from. DeployOpen does not publish prices, and no fee is given without a written scope.

How long does this work take, and what sets the duration?

Duration is set by the number of workloads to review, the state of existing labels and zone topology, and how many test cycles are needed in a non-production environment. Services that already run with several replicas and clear ownership move faster than services that depend on zonal storage or single-replica designs. Autoscaling behavior and any change windows also extend the schedule. No timeline is given here because it depends on the agreed scope, and the written scope is where the schedule is set.

What does the work need from our team?

The work needs a few things from your side before it starts:

Can our in-house platform team do this without a partner?

Yes, a team that already runs Kubernetes in production can implement topology spread constraints and anti-affinity without outside help, particularly for a small number of services. The harder parts are testing failure scenarios safely, checking that autoscaler and scheduler behavior matches the design, and documenting the result for audit and operations. Teams that lack spare capacity to run drain and zone-loss tests, or that have many services with mixed storage types, often bring in a partner for the design and verification phase. Your team can also keep ownership of the rules after the work, and the written scope should say who maintains them.

How do spread rules interact with etcd latency across zones?

Spread rules only place workloads. They do not change the control plane. etcd members that span zones carry round-trip latency on every write, and the Kubernetes documentation recommends an odd number of members, with five members in production. Spreading application pods across zones is a separate decision from spreading etcd across zones. Confirm the latency your etcd members will see before deciding whether control plane nodes should span zones, and see the sibling topic on running Kubernetes across multiple zones for the failure cases each layout survives.

How should spread rules work with pod disruption budgets during drains?

Spread rules control where pods start, while disruption budgets control how many can be taken down at once during voluntary disruptions such as node drains and upgrades. The two must agree. A spread rule set to hard requirements can leave no schedulable placement during a drain, and a budget that allows zero unavailable pods can block a drain entirely. Test both together in staging, and check the budget values against the replica count per zone. The sibling topic on pod disruption budgets covers the budget side in more detail.

Does the cluster autoscaler change how spread rules behave?

Yes. When spread rules cannot be met, the scheduler leaves pods pending, and the autoscaler must add a node in the right zone to satisfy them. If node groups are not split by zone, the autoscaler may add capacity that does not help the spread. Ask whether node pools are zone-specific, how scale-down decisions respect spread, and how the autoscaler is configured to handle pods that stay pending. These checks belong in the scope, because they decide whether the autoscaler helps or works against the rules.

Which questions should we ask a partner before signing?

Ask for a written scope that names the clusters, zones, services and autoscaler in use, along with the deliverables, the test method and the retest plan. Ask how zone-loss and node-drain tests will run in non-production environments before any change reaches production. Ask who keeps the labels, rules and documentation up to date after handover. DeployOpen delivers most engagements as fixed-scope work, with scope, deliverables and timelines agreed in writing before work starts, and ongoing support is available as a retainer.

What to confirm in your environment before relying on spread rules

Topology spread constraints only work as designed when the cluster has the version, failure domains, storage layout, control plane placement and scheduling settings the rules assume. Confirm each item below with your distribution's documentation and your own cluster, not with general statements about Kubernetes.

Minor version and supported fields

Confirm which Kubernetes minor version your distribution ships and that the scheduler accepts the topology spread fields you plan to use, including whenUnsatisfiable and matchLabelKeys. Field behavior has changed across releases, so check the release notes for your version. Kubernetes maintains only the three most recent minor releases, so an older cluster may also be near end of life. Run kubectl explain pod.spec.topologySpreadConstraints against the live API server to confirm the schema.

Kubernetes releases

Distinct zones and failure domains

A constraint across zones does nothing useful if the cluster has only one zone or if nodes lack the zone label. Check that every worker carries the topology label you plan to spread on, such as topology.kubernetes.io/zone, and that each label value maps to a real failure domain. Count the distinct values and compare them with your replica count and maxSkew. Ask your infrastructure team whether two labeled zones share a power feed, network path or hypervisor cluster.

Zonal persistent volumes

Many block storage classes create volumes bound to one zone. A pod that restarts in another zone then cannot mount its volume, and the spread rule may be ignored or leave the pod pending. Check the volumeBindingMode of each StorageClass, whether the storage backend is zonal or replicated across zones, and how your CSI driver handles topology. Stateful services need this review more than stateless ones.

Control plane and etcd placement

Spreading application pods across zones does not spread the control plane. Confirm where the kube-apiserver, kube-controller-manager, scheduler and etcd members run, and whether each etcd member sits in a different failure domain. The kubeadm HA guide describes stacked and external etcd topologies with at least three control plane nodes, so verify the topology you built. A zone outage that removes two etcd members can stop writes even when every application replica survives.

kubeadm HA guide

Autoscaler and scheduler configuration

Cluster autoscalers add nodes based on pending pods, and a spread rule can hold pods pending if the new node lands in a zone the autoscaler is not configured to grow. Check that your node groups exist in every zone you spread across and that the autoscaler's balancing options match your intent. Also check for a default scheduler profile or cluster-level default spread constraints that could override workload settings. Test a scale-up and a node drain in a staging cluster before you trust the result.

How DeployOpen works on this

DeployOpen plans and implements spread and availability controls for self-hosted Kubernetes clusters in infrastructure you control. The work starts from your failure domains and service requirements, then moves through a written scope, a tested build and a handover your own platform team can operate.

How we scope

  • Map which zones, racks or data centers your nodes and storage actually sit in before choosing any spread rule.
  • Agree in writing which services need zone spread, node spread or both, and which can tolerate reduced replicas.
  • Confirm autoscaler, node pool and storage class constraints so spread rules do not block scale-out or volume attachment.

How we build

  • Set topology spread constraints and anti-affinity on each workload, with maxSkew and whenUnsatisfiable values chosen per service.
  • Test node drains and simulated zone loss in a non-production cluster and record how pods reschedule.
  • Pair spread settings with pod disruption budgets and node labels so maintenance and failures follow the same rules.

How we hand over

  • Deliver manifests in your Git repository with comments explaining each spread decision and its trade-off.
  • Document the failure scenarios tested, the expected pod placement and the steps to verify placement after changes.
  • Walk your platform and operations teams through checking spread status and troubleshooting Pending pods.

How we support

  • Review spread settings when you add node pools, zones or autoscaling policies, as part of the written scope.
  • Retest placement after Kubernetes upgrades, since scheduler behavior and labels can change between releases.
  • Ongoing support, upgrades and continuous testing are available as a retainer, priced from the written scope.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.