✦ For everyone, free.

Practical knowledge for real and everyday life

Home

Kubernetes Pod Affinity Placement

Kubernetes Pod Affinity Placement ensures pods are scheduled based on predefined rules, optimizing resource usage and application performance in a cluster.

Kubernetes Pod Affinity Placement is a scheduling mechanism that constrains where a Pod may be placed based on the labels of other Pods already running in the cluster, rather than based on node labels directly — allowing a Pod to require or prefer being co-located, within a specified topology domain, with Pods matching a given label selector. Configured through spec.affinity.podAffinity, this mechanism inverts the usual node-centric placement logic: instead of asking "does this node have the right labels," it asks "are there Pods with the right labels near this node," making it the tool of choice for co-locating cooperating workloads that benefit from proximity — reduced network latency, shared local caches, or data locality.

Like node affinity, pod affinity supports both a hard requiredDuringSchedulingIgnoredDuringExecution variant and a soft preferredDuringSchedulingIgnoredDuringExecution variant, and its rules are always evaluated relative to a specified topology domain rather than to an individual node in isolation.


The Topology Key Concept

Defining the Scope of "Nearby"

Every pod affinity rule includes a topologyKey, a node label (commonly kubernetes.io/hostname for same-node co-location, or topology.kubernetes.io/zone for same-zone co-location) that defines the granularity at which "affinity" is evaluated — the rule is satisfied if a node sharing that topology key's value with at least one node running a matching Pod exists, not merely if the exact same node happens to host both.

affinity:
  podAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
            - key: app
              operator: In
              values: ["codartium-cache"]
        topologyKey: "kubernetes.io/hostname"

This rule requires the new Pod to be scheduled onto the same node (kubernetes.io/hostname) as an existing Pod labeled app: codartium-cache.


Required Pod Affinity

Hard Co-Location Requirements

A required pod affinity rule filters out any node that does not share the specified topology domain with at least one Pod matching the label selector — a workload that genuinely cannot function correctly without being co-located with its dependency (a sidecar-like helper that must share the same node to access a local Unix socket, for instance, though this specific case is more commonly solved with an actual sidecar container) uses this hard variant.

Namespace Scoping

By default, pod affinity matches Pods only within the same namespace as the Pod being scheduled, unless namespaces (or, in newer versions, namespaceSelector) is explicitly set to broaden the match across specified namespaces — an important detail when co-location needs to span workloads managed in different namespaces.

affinity:
  podAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchLabels:
            app: codartium-cache
        namespaces: ["codartium-infra"]
        topologyKey: "kubernetes.io/hostname"

Preferred Pod Affinity

Soft Co-Location Preferences

The more commonly used variant in practice: a weighted preference for placing a Pod near matching Pods, without hard-blocking placement elsewhere if no such node is available.

affinity:
  podAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 60
        podAffinityTerm:
          labelSelector:
            matchLabels:
              app: codartium-frontend
          topologyKey: "topology.kubernetes.io/zone"

This expresses "prefer scheduling in the same zone as codartium-frontend Pods, to reduce cross-zone network traffic and its associated latency and cost, but don't refuse to schedule elsewhere if no such zone is viable."


Common Use Cases

Reducing Cross-Zone Network Costs

Preferring same-zone placement between a service and its most frequently accessed dependency reduces both latency and, on cloud providers charging for cross-zone traffic, direct cost — a very common, practical application of soft pod affinity.

Co-Locating for Shared Local Resources

Workloads that benefit from sharing a node-local cache or resource with a specific companion Pod (without the tighter, more disruptive coupling of an actual sidecar container) use required or strongly weighted pod affinity to encourage that co-location.


Performance Considerations

Cost of Evaluation at Scale

Because pod affinity requires inspecting the labels of other running Pods (rather than simply checking static node labels), it is computationally more expensive to evaluate than node affinity, particularly in very large clusters with many Pods — this is a known scalability consideration, and clusters with extremely high Pod counts sometimes limit or discourage widespread required pod affinity rules specifically because of this added scheduling overhead.


Example

apiVersion: v1
kind: Pod
metadata:
  name: codartium-podaffinity-example
  labels:
    app: codartium-worker
spec:
  affinity:
    podAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
        - weight: 80
          podAffinityTerm:
            labelSelector:
              matchLabels:
                app: codartium-cache
            topologyKey: "kubernetes.io/hostname"
  containers:
    - name: worker
      image: codartium/worker:latest