Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 361 of 8025. Advanced Kubernetes ConfigurationFree lesson

Optimizing Cluster Utilization with Topology Spread Constraints

Distribute pods across availability zones or rack domains to maintain balanced load and prevent single points of failure within the cluster.

In this lesson, you will learn how to use topologySpreadConstraints to automatically balance your pods across different failure domains like availability zones or physical racks.

Moving Beyond Simple Anti-Affinity

While podAntiAffinity is great for ensuring two pods don't land on the same node, it acts as a "hard" rule that can sometimes lead to scheduling failures or "clumping" in complex multi-zone environments. topologySpreadConstraints offers a more nuanced approach. Instead of just saying "don't put these together," you are saying, "distribute these pods as evenly as possible across my infrastructure."

How it Works

This mechanism monitors the distribution of your pods based on a specific label. You define a topologyKey (such as topology.kubernetes.io/zone or kubernetes.io/hostname) and a maxSkew. The maxSkew represents the maximum allowed difference in the number of pods between any two topology domains.

Consider a scenario where you have a three-zone cluster and want to deploy six replicas of a stateful service:

spec:
  topologySpreadConstraints:
    - maxSkew: 1
      topologyKey: "topology.kubernetes.io/zone"
      whenUnsatisfiable: DoNotSchedule
      labelSelector:
        matchLabels:
          app: my-distributed-db

In this configuration, Kubernetes will ensure that if you have 6 pods, each zone gets exactly 2 pods. If one zone goes offline, the scheduler will strive to keep the remaining pods evenly split across the surviving zones. By setting whenUnsatisfiable: DoNotSchedule, you tell Kubernetes to prioritize high availability over "blindly" starting a pod if it cannot maintain the desired balance.

Why This Matters

For distributed databases or high-availability microservices, this is critical. It prevents the "noisy neighbor" or "single point of failure" scenarios where an entire application replica set accidentally clusters onto a single zone or rack. By spreading them, you ensure that a single localized outage doesn't take down your entire workload, maintaining stable performance and redundancy across your entire hardware footprint.

Key Takeaway: Use topologySpreadConstraints to enforce even distribution of pods across failure domains, providing a more flexible and reliable alternative to strict anti-affinity rules.