Scheduling Pods Relative to Other Pods
Node Affinity answers "which nodes?" but sometimes you need to answer "near which other Pods?" or "away from which other Pods?" This is what Pod Affinity and Pod Anti-Affinity solve.
- Pod Affinity: "Schedule me on the same node (or zone) as Pods matching label X." Use this when two services communicate heavily and latency matters — for example, co-locating a cache sidecar with its application.
- Pod Anti-Affinity: "Schedule me on a different node (or zone) from Pods matching label X." Use this to spread replicas of the same service across nodes for fault tolerance.
Like Node Affinity, both come in required (hard) and preferred (soft) variants.
Pod Anti-Affinity Example: Spreading Replicas
This is the most common use case. You want to ensure no two replicas of your service land on the same node — a required pod anti-affinity rule matching the service's own label, scoped by a topologyKey. The topologyKey: kubernetes.io/hostname means "treat each unique hostname as a separate domain." The rule reads: "Do not schedule this Pod on any node that already has a Pod with app=auth-service."
Pod Affinity Example: Co-location
A preferred pod affinity term, weighted at maximum priority and matching against a cache service's label, scoped to the same hostname-level topology key, tells the scheduler: "Strongly prefer placing this Pod on the same node as a redis-cache Pod." If no node has a redis-cache Pod, the scheduler will still place the Pod somewhere.
The Scalability Warning
Pod Affinity and Anti-Affinity are computationally expensive. The scheduler must evaluate every existing Pod's labels against every candidate node. In clusters with thousands of nodes and tens of thousands of Pods, this can significantly slow scheduling. For the common use case of "spread replicas across zones," Topology Spread Constraints (covered next) are more efficient and should be preferred.