Anti-Affinity

Difficulty: Advanced

Question

What is Pod anti-affinity, how do you configure it, and how does it help with high availability?

Answer

Pod anti-affinity tells the scheduler to keep certain Pods apart, usually replicas of the same app, so they do not land on the same node or zone. If all replicas sit on one node and that node fails, the whole service goes down; spreading them across failure domains means one failure only takes out part of the capacity.

How the rule is expressed

Anti-affinity lives under spec.affinity.podAntiAffinity and has three key parts:

  • labelSelector: which Pods to avoid, typically the same app label as this Pod
  • topologyKey: the node label that defines a domain. kubernetes.io/hostname means "not on the same node"; topology.kubernetes.io/zone means "not in the same zone".
  • Hard or soft:
  • requiredDuringSchedulingIgnoredDuringExecution is a strict rule. If it cannot be satisfied, the Pod stays Pending.
  • preferredDuringSchedulingIgnoredDuringExecution is a scored preference with a weight from 1 to 100. The scheduler tries to honour it but will co-locate Pods if needed.

IgnoredDuringExecution means the rule is only checked when scheduling. Pods already running are not moved if conditions change later.

Choosing required vs preferred

A required per-node rule with 5 replicas needs at least 5 eligible nodes. If you scale to 6 on a 5-node cluster, one Pod stays Pending, and during a rolling update the surge Pod may also be blocked. Common practice:

  • Required across nodes for small, critical sets like a 3-member etcd, ZooKeeper or Redis Sentinel group, where two members on one node defeats the purpose
  • Preferred for stateless web replicas, so the service can still scale when the cluster is short on nodes

Anti-affinity vs topology spread constraints

AspectPod anti-affinitytopologySpreadConstraints
ModelAt most one matching Pod per domain (hard) or best effortKeep counts balanced within maxSkew
Many replicasBreaks once replicas exceed domains (required)Spreads evenly, for example 4-3-3 over 3 zones
Behaviour when impossiblePending or ignoredDoNotSchedule or ScheduleAnyway

For "spread 12 replicas evenly across 3 zones", topology spread constraints are the better tool. Many teams use both: spread across zones and prefer distinct nodes within a zone.

Gotchas and real-world use

  • Inter-pod affinity and anti-affinity require the scheduler to check existing Pods on many nodes, which is expensive in very large clusters, so use it where it matters.
  • The labelSelector must match the Pod's own labels, or the rule does nothing.
  • Anti-affinity controls placement, not voluntary disruptions. Pair it with a PodDisruptionBudget so a node drain does not evict all replicas at once.
  • For a UPI payment service in ap-south-1, a typical setup is 3 or more replicas, zone spreading, preferred per-node anti-affinity and a PDB with minAvailable: 2.

Code examples

Hard per-node and soft per-zone anti-affinity

apiVersion: apps/v1
kind: Deployment
metadata:
  name: payments-api
spec:
  replicas: 3
  selector:
    matchLabels: { app: payments-api }
  template:
    metadata:
      labels: { app: payments-api }
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchLabels: { app: payments-api }
              topologyKey: kubernetes.io/hostname      # never 2 on one node
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              podAffinityTerm:
                labelSelector:
                  matchLabels: { app: payments-api }
                topologyKey: topology.kubernetes.io/zone  # try different zones
      containers:
        - name: api
          image: ghcr.io/acme/payments-api:3.2.1

Each replica must be on a different node and the scheduler prefers different zones. Note that the preferred form wraps the term in podAffinityTerm.

Even spreading with topology spread constraints

spec:
  topologySpreadConstraints:
    - maxSkew: 1
      topologyKey: topology.kubernetes.io/zone
      whenUnsatisfiable: DoNotSchedule
      labelSelector:
        matchLabels: { app: payments-api }

Zone counts never differ by more than one, which scales cleanly to many replicas, unlike required anti-affinity.

Key points

  • Anti-affinity keeps matching Pods apart across a topology domain
  • topologyKey kubernetes.io/hostname = per node; topology.kubernetes.io/zone = per zone
  • required = hard rule (can leave Pods Pending); preferred = weighted best effort
  • Checked only at scheduling time (IgnoredDuringExecution)
  • Use topologySpreadConstraints for even spreading of many replicas, and a PDB for drains

Common follow-up questions

  • What happens if you scale a Deployment with required per-node anti-affinity beyond the node count?
  • How do topology spread constraints differ from anti-affinity?
  • How would you co-locate a cache with the app that uses it?
  • How does a PodDisruptionBudget complement anti-affinity?

Interview tips

  • Explain topologyKey clearly; it is the part most candidates cannot describe
  • Discuss required vs preferred and the Pending-Pod risk
  • Mention topology spread constraints and PDBs to show a complete HA picture

Concepts covered

Pod Anti-Affinity, topologyKey, High Availability, Topology Spread Constraints, Failure Domains

More Kubernetes & Orchestration questions