Get in Touch
Close

Your Cloud Story,
Engineered for Success

Contacts

US Office: Obsium, 6200,
Stoneridge Mall Rd, Pleasanton CA 94588 USA

Kochi Office: GB4, Ground Floor, Athulya, Infopark Phase 1, Infopark Campus Kakkanad, Kochi 682042

+91 9895941969

hello@obsium.io

Kubernetes Affinity and Anti-Affinity

Kubernetes Affinity and Anti-Affinity

Understanding Kubernetes Affinity and Anti-Affinity

Affinity and anti-affinity rules give Pods a way to express preferences or requirements about which nodes they run on, and how they should be placed relative to other Pods. There are two categories: node affinity, which matches a Pod against node labels, and inter-pod affinity/anti-affinity, which matches a Pod against the labels of other Pods already running in the cluster. Both come in two strengths: requiredDuringSchedulingIgnoredDuringExecution (a hard rule the scheduler must satisfy) and preferredDuringSchedulingIgnoredDuringExecution (a soft rule the scheduler tries to satisfy but can ignore if necessary).

How It Works

Node affinity is defined in spec.affinity.nodeAffinity and uses matchExpressions against node labels, similar to but more expressive than a plain nodeSelector (supporting operators like In, NotIn, Exists). Inter-pod affinity, defined in spec.affinity.podAffinity or podAntiAffinity, uses a labelSelector to match other Pods and a topologyKey (such as kubernetes.io/hostname or topology.kubernetes.io/zone) to define the scope of nearby – same node, same zone, or same region.

Simple Example

A team running a Redis cluster wants its three replicas spread across different nodes so a single node failure never takes down more than one replica. They add a podAntiAffinity rule with requiredDuringSchedulingIgnoredDuringExecution, a labelSelector matching app: redis, and topologyKey: kubernetes.io/hostname. The scheduler now refuses to place two redis Pods on the same node. Separately, a latency-sensitive API might use podAffinity to co-locate with its cache Pods on the same node, reducing network hops, while nodeAffinity ensures both only run on nodes labeled instance-type: memory-optimized.

Common Use Cases

High Availability Spreading

Anti-affinity keeps replicas of a stateful or critical service off the same node or zone, reducing correlated failure risk.

Co-locating Related Workloads

Affinity pulls latency-sensitive services or sidecars close to the services they depend on.

Steering to Specialized Hardware

Node affinity routes workloads to nodes with specific labels like GPU type, instance family, or zone, often paired with taints for hard exclusion.

Benefits of Affinity Rules

  • Expresses placement intent declaratively instead of manually assigning Pods to nodes.
  • Improves resilience by spreading critical replicas across failure domains (nodes, zones).
  • More flexible than a plain nodeSelector, supporting set-based matching and soft preferences.

Limitations and Risks

  • Inter-pod affinity and anti-affinity, especially required rules with a broad topologyKey, can be computationally expensive to evaluate in large clusters and slow scheduling.
  • Overly strict required rules can leave Pods permanently Pending if the ideal placement doesn’t exist – common when anti-affinity for three replicas is combined with a cluster that only has two eligible nodes.
  • Topology spread constraints, a newer, related API, often achieve even spreading more predictably than anti-affinity and are worth considering as an alternative.
  • Preferred rules can be silently ignored under resource pressure, so relying on them for critical resilience guarantees is risky without also monitoring actual Pod distribution.

Best Practices

  • Use preferredDuringScheduling for most anti-affinity cases so Pods can still be scheduled during capacity crunches; reserve required rules for hard resilience requirements you’re willing to trade availability for.
  • Consider topologySpreadConstraints instead of or alongside anti-affinity for more even and predictable distribution across zones or nodes.
  • Keep inter-pod affinity/anti-affinity label selectors narrow and topologyKey choice intentional (node vs zone) to control both correctness and scheduler performance.
  • Test affinity rules in a staging cluster with realistic node counts before relying on them in production, since behavior changes significantly with cluster size.
  • Combine node affinity with taints/tolerations when hard exclusion is also required – affinity alone doesn’t prevent other Pods from landing on the same nodes.

Frequently Asked Questions

What is Kubernetes Affinity and Anti-Affinity?

Kubernetes affinity and anti-affinity rules let Pods express required or preferred placement relative to node labels or other running Pods, controlling co-location and spreading across the cluster.

How does Kubernetes Affinity and Anti-Affinity work?

Kubernetes Affinity and Anti-Affinity works by combining the components described in the sections above. The main page walks through the architecture, the typical use cases, and the trade-offs to weigh before adopting it.

Why does Kubernetes Affinity and Anti-Affinity matter?

Teams adopt Kubernetes Affinity and Anti-Affinity to ship faster, run more reliably, and reduce the cognitive load on engineers. The benefits, limits, and adjacent tools are covered in the body above.

When should you use Kubernetes Affinity and Anti-Affinity?

Use Kubernetes Affinity and Anti-Affinity when the problems it solves match what your team is hitting today. The page above outlines the signals that mean you should adopt it now, and the cases where a simpler approach is fine.