Kubernetes Affinity vs Anti-Affinity Explained (with Real AWS EKS Examples)

Kubernetes Projects Part 18 DevOps Docs Explore in Brain
Audio Ready
Listen to this article
0:00 --:--

Kubernetes Affinity vs Anti-Affinity Explained (with Real AWS EKS Examples)

By default, the Kubernetes scheduler looks at your cluster’s nodes, finds one with enough CPU and memory, and drops your Pod there. For simple stateless apps, that works fine.

But in production, “just put it anywhere” breaks down fast:

  • You want GPU workloads to land only on GPU machines.
  • You want payment services nowhere near volatile Spot instances.
  • You want a web app to sit close to its Redis cache so requests stay fast.
  • You want your API replicas spread across different Availability Zones so one outage doesn’t take down your whole service.

That is what Affinity and Anti-Affinity solve.

In simple terms:

  • Affinity attracts Pods toward specific nodes or other Pods.
  • Anti-Affinity pushes (repels) Pods away from specific nodes or other Pods.

Both rules live inside a Pod’s spec.affinity field and give the Kubernetes scheduler fine-grained control over where your workloads run.


The Big Picture: 4 Ways to Control Placement

Think of Kubernetes placement rules across two dimensions:

  1. What are you matching against? A Node (hardware, instance type, zone) or another Pod (an app or cache already running somewhere).
  2. Do you want them together or apart? Affinity (together) or Anti-Affinity (apart).
flowchart TB
    Root["spec.affinity"]
    Root --> Node["Targeting Nodes<br/>Uses node labels"]
    Root --> Pod["Targeting Other Pods<br/>Uses pod labels + topologyKey"]

    Node --> NA["Node Affinity<br/>Operators: In, Exists<br/>Attract Pods to matching nodes"]
    Node --> NAA["Node Anti-Affinity<br/>Operators: NotIn, DoesNotExist<br/>Keep Pods off specific nodes"]

    Pod --> PA["Pod Affinity<br/>podAffinity<br/>Co-locate Pods in same zone or node"]
    Pod --> PAA["Pod Anti-Affinity<br/>podAntiAffinity<br/>Spread Pods across zones or nodes"]

    style Root fill:#0f172a,stroke:#38bdf8,stroke-width:2px,color:#f8fafc
    style Node fill:#1e293b,stroke:#94a3b8,stroke-width:1.5px,color:#f8fafc
    style Pod fill:#1e293b,stroke:#94a3b8,stroke-width:1.5px,color:#f8fafc
    style NA fill:#064e3b,stroke:#10b981,stroke-width:1.5px,color:#f8fafc
    style NAA fill:#450a0a,stroke:#ef4444,stroke-width:1.5px,color:#f8fafc
    style PA fill:#1e1b4b,stroke:#818cf8,stroke-width:1.5px,color:#f8fafc
    style PAA fill:#451a03,stroke:#f59e0b,stroke-width:1.5px,color:#f8fafc

Let’s break down each of the four behaviors in plain English.


Core Differences

1. Node Affinity (nodeAffinity)

Attracts Pods to nodes based on node labels.

For example, if you label your GPU machines with gpu=true, you can use nodeAffinity to tell Kubernetes: “Only schedule this machine-learning Pod on nodes labeled gpu=true.”

2. Node Anti-Affinity

Keeps Pods off specific nodes.

Interestingly, Kubernetes does not have a separate nodeAntiAffinity field. Instead, you achieve node anti-affinity right inside nodeAffinity by using negative operators like NotIn or DoesNotExist. For example, you can keep workloads off older machines labeled tier=legacy.

3. Pod Affinity (podAffinity)

Places Pods together in the same neighborhood (topology domain) as other running Pods.

Instead of looking at node labels, podAffinity looks at the labels of already-running Pods. A “topology domain” (set by topologyKey) defines the boundary — for example:

  • kubernetes.io/hostname = same node
  • topology.kubernetes.io/zone = same Availability Zone

This reduces network latency for tightly coupled services, such as placing a web server right next to its Redis cache.

4. Pod Anti-Affinity (podAntiAffinity)

Spreads Pods apart across different topology domains so they do not sit next to matching Pods.

This is your go-to tool for High Availability. By telling Kubernetes “never put two replicas of my app in the same node or Availability Zone,” you eliminate single points of failure.


Comparison Matrix

Feature Affinity (Node & Pod) Anti-Affinity (Node & Pod)
Scheduling Behavior Attracts and co-locates workloads. Repels and separates workloads.
Primary Goal Hardware matching or low-latency communication. High availability, fault tolerance, or workload isolation.
Typical Use Case Placing an app on SSD nodes or alongside a cache. Spreading replicas across different availability zones.
Node-Level Syntax nodeAffinity with In / Exists operators. nodeAffinity with NotIn / DoesNotExist operators.
Pod-Level Syntax podAffinity with labelSelector and topologyKey. podAntiAffinity with labelSelector and topologyKey.

Hard Rules vs. Soft Rules

Kubernetes gives you two strictness levels for both affinity and anti-affinity. The field names look intimidating at first, so read them as two halves glued together:

  1. First half (requiredDuringScheduling vs preferredDuringScheduling): Should the scheduler treat this as a strict law or a preference?
  2. Second half (IgnoredDuringExecution): What happens if labels change after the Pod is already running?
flowchart LR
    Start["Pod waiting to be scheduled"] --> Check{"Rule Type?"}
    Check -- "Hard Rule<br/>requiredDuringScheduling..." --> MatchHard{"Matching node<br/>available?"}
    MatchHard -- Yes --> Run1["Pod Scheduled"]
    MatchHard -- No --> Pending["Pod stays Pending<br/>until a matching node exists"]

    Check -- "Soft Rule<br/>preferredDuringScheduling..." --> MatchSoft{"Matching node<br/>available?"}
    MatchSoft -- Yes --> Run2["Pod Scheduled on<br/>highest-weight match"]
    MatchSoft -- No --> Fallback["Pod Scheduled on<br/>any healthy node"]

    style Start fill:#1e293b,stroke:#94a3b8,color:#f8fafc
    style Check fill:#1e1b4b,stroke:#818cf8,color:#f8fafc
    style MatchHard fill:#312e81,stroke:#818cf8,color:#f8fafc
    style MatchSoft fill:#312e81,stroke:#818cf8,color:#f8fafc
    style Run1 fill:#064e3b,stroke:#10b981,color:#f8fafc
    style Run2 fill:#064e3b,stroke:#10b981,color:#f8fafc
    style Fallback fill:#065f46,stroke:#34d399,color:#f8fafc
    style Pending fill:#450a0a,stroke:#ef4444,color:#f8fafc

Hard Rules (requiredDuringSchedulingIgnoredDuringExecution)

  • The scheduler must satisfy the rule.
  • If no node matches the condition, the Pod stays stuck in a Pending state.
  • Use when: Running on the wrong node would break the app or cause serious issues (for example, running a GPU app without a GPU, or putting a database on a Spot instance).

Soft Rules (preferredDuringSchedulingIgnoredDuringExecution)

  • The scheduler tries to satisfy the rule, scoring candidate nodes using a weight from 1 to 100.
  • If no matching node has room, the scheduler still runs the Pod on another available node instead of leaving it Pending.
  • Use when: You want cost optimization or better latency, but uptime matters more than strict placement.

What does IgnoredDuringExecution mean? It means Kubernetes only checks these rules at scheduling time. If you change a node label or a Pod label after a Pod is already running, Kubernetes will not evict or kill the running Pod.


4 Real AWS EKS Examples

In an AWS Elastic Kubernetes Service (EKS) cluster, you get helpful labels right out of the box — such as eks.amazonaws.com/capacityType (for Spot vs. On-Demand nodes) and topology.kubernetes.io/zone (for the AWS Availability Zone).

Here are four real-world EKS manifests covering every scheduling behavior.


1. Node Affinity: Targeting EC2 Spot Instances

When running stateless, fault-tolerant batch jobs on EKS, you can save up to 90% on compute costs by directing Pods to EC2 Spot Instances. EKS automatically labels managed Spot nodes with eks.amazonaws.com/capacityType: SPOT.

Using a soft rule (preferredDuringSchedulingIgnoredDuringExecution) is ideal here: your batch workers prefer cheap Spot nodes, but if AWS runs out of Spot capacity in that region, they gracefully fall back to On-Demand nodes instead of stalling.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: batch-worker
spec:
  replicas: 3
  selector:
    matchLabels:
      app: batch-worker
  template:
    metadata:
      labels:
        app: batch-worker
    spec:
      affinity:
        nodeAffinity:
          # Prefer Spot nodes, but fall back to On-Demand if Spot capacity is unavailable
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              preference:
                matchExpressions:
                  - key: eks.amazonaws.com/capacityType
                    operator: In
                    values:
                      - SPOT
      containers:
        - name: worker
          image: busybox
          command: ["sh", "-c", "sleep 3600"]

2. Node Anti-Affinity: Keeping Critical Apps Off Spot Instances

For stateful or mission-critical workloads like databases or payment processors, you want to avoid EC2 Spot nodes completely because AWS can reclaim them with just a two-minute interruption notice.

To prevent payment-service Pods from landing on volatile Spot instances, use nodeAffinity with a hard rule and the NotIn operator targeting eks.amazonaws.com/capacityType: SPOT:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: payment-service
spec:
  replicas: 2
  selector:
    matchLabels:
      app: payment-service
  template:
    metadata:
      labels:
        app: payment-service
    spec:
      affinity:
        nodeAffinity:
          # Strictly block Spot nodes; only schedule on non-Spot nodes
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
              - matchExpressions:
                  - key: eks.amazonaws.com/capacityType
                    operator: NotIn
                    values:
                      - SPOT
      containers:
        - name: payment-api
          image: nginx:alpine
          ports:
            - containerPort: 8080

Why NotIn: ["SPOT"] instead of In: ["ON_DEMAND"]? Using NotIn on SPOT works even if your cluster also has self-managed or custom nodes that don’t carry the eks.amazonaws.com/capacityType label. It guarantees one thing clearly: never put this Pod on a Spot instance.


3. Pod Affinity: Co-locating an App with Redis in the Same AZ

In AWS, sending traffic across different Availability Zones adds network latency and costs extra per gigabyte in cross-AZ data transfer fees.

If your frontend service talks heavily to an in-memory cache (redis-cache), you can configure podAffinity using topology.kubernetes.io/zone to schedule your frontend Pods in the exact same Availability Zone as your Redis Pods:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: frontend
spec:
  replicas: 3
  selector:
    matchLabels:
      app: frontend
  template:
    metadata:
      labels:
        app: frontend
    spec:
      affinity:
        podAffinity:
          # Try to place frontend Pods in the same AZ as redis-cache Pods
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              podAffinityTerm:
                labelSelector:
                  matchExpressions:
                    - key: app
                      operator: In
                      values:
                        - redis-cache
                topologyKey: topology.kubernetes.io/zone
      containers:
        - name: frontend
          image: nginx:alpine
          ports:
            - containerPort: 80

Here, labelSelector finds where app: redis-cache is already running, and topologyKey: topology.kubernetes.io/zone tells the scheduler: “Put frontend in the same AWS Availability Zone as that Redis Pod.”


4. Pod Anti-Affinity: Spreading Replicas Across AWS Availability Zones

If all 3 replicas of your core-api end up in us-east-1a and that zone has an outage, your entire API goes down.

To ensure High Availability, use podAntiAffinity with topology.kubernetes.io/zone so each replica of core-api runs in a different AWS Availability Zone:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: core-api
spec:
  replicas: 3
  selector:
    matchLabels:
      app: core-api
  template:
    metadata:
      labels:
        app: core-api
    spec:
      affinity:
        podAntiAffinity:
          # Keep replicas in separate AWS Availability Zones
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchExpressions:
                  - key: app
                    operator: In
                    values:
                      - core-api
              topologyKey: topology.kubernetes.io/zone
      containers:
        - name: core-api
          image: nginx:alpine
          ports:
            - containerPort: 80

Watch out when scaling past 3 replicas! A hard requiredDuringSchedulingIgnoredDuringExecution rule on a 3-AZ AWS region means only 1 replica per AZ can ever run (maximum 3 Pods). If you scale core-api to 4 replicas, the 4th Pod will stay stuck in Pending because every AZ already has a core-api Pod.

If you plan to scale beyond your zone count, switch to preferredDuringSchedulingIgnoredDuringExecution or use Kubernetes Pod Topology Spread Constraints (topologySpreadConstraints) to spread Pods evenly across zones without hard-blocking extra replicas.


Quick Verification & Debugging Commands

Once you apply a manifest, here are three quick commands to verify your Pods landed where you expected (or figure out why one is stuck in Pending):

  1. Check node labels in your cluster (great for verifying EKS Spot or AZ labels):
    kubectl get nodes --show-labels
    
  2. See which node each Pod landed on:
    kubectl get pods -o wide
    
  3. Debug a Pod stuck in Pending:
    kubectl describe pod <pod-name>
    

    Look at the Events section at the bottom. If an affinity rule blocked scheduling, you will see a clear FailedScheduling message such as 0/6 nodes are available: 6 node(s) didn't match Pod's node affinity/selector.


Summary: Which One Should You Pick?

  • Want specific hardware or pricing (GPU, SSD, Spot)? Use Node Affinity (In / Exists).
  • Want to ban a workload from certain nodes (Spot, legacy)? Use Node Anti-Affinity (nodeAffinity with NotIn / DoesNotExist).
  • Want two services close together for speed and lower AWS cross-AZ fees? Use Pod Affinity (podAffinity).
  • Want replicas separated for High Availability? Use Pod Anti-Affinity (podAntiAffinity) — and remember to use preferred rules or topologySpreadConstraints if your replica count is higher than your number of Availability Zones.

If you are running autoscaling on EKS alongside these scheduling rules, check out the Karpenter guide to see how EKS provisions the right nodes automatically based on your Pod requirements.

Jatin Sharma
DevOps Engineer & Platform Architect. Passionate about cloud-native systems, automation, observability, and GitOps.