Wednesday, May 27, 2026

Kubernetes Topology Spread Constraints

Topology spread constraints are rules in Kubernetes used to control how Pods are distributed across your cluster's failure domains (such as regions, zones, or specific nodes). They ensure high availability and efficient resource utilization by preventing all replicas of an application from being concentrated in a single location.

Why Use Them?

Without topology constraints, a scaling event or node failure could take down your application if all pods land on the same host or availability zone. By defining these constraints, you ensure that Pods are spread evenly.

Core Components

A topology spread constraint requires a few key parameters:

topologyKey

The node label used to define the topology domain (e.g., kubernetes.io/hostname for nodes, or topology.kubernetes.io/zone for availability zones).

maxSkew

The maximum allowed difference in the number of Pods between any two topology domains. For example, if maxSkew is 1, and you have two zones, one zone can have 4 pods and the other 5, but not 3 and 5.

whenUnsatisfiable

Tells the scheduler what to do if the constraint cannot be met. You can choose to DoNotSchedule (reject the pod until the cluster changes) or ScheduleAnyway (place it regardless, prioritizing the most balanced node available).

labelSelector

Identifies which set of Pods the constraint applies to (usually based on their labels).

Example Configuration

Here is how you define a topologySpreadConstraints rule in a Deployment or ReplicaSet to spread pods evenly across different zones:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: DoNotSchedule
        labelSelector:
          matchLabels:
            app: web
      containers:
      - name: web-container
        image: nginx

Topology Spread vs. Pod Anti-Affinity

While Pod Anti-Affinity is often used to prevent Pods from landing on the same node, it is an "all-or-nothing" binary rule. Topology Spread Constraints provide a much more flexible and gradual approach. Instead of just blocking co-location, they allow you to fine-tune exactly how uneven the distribution (skew) can be across your infrastructure.

No comments:

Post a Comment

Getting environment variables in React app

To get environment variables in React, the method depends on the tool you used to build your project. React environment vari...