In this lesson, you will learn how to use Pod Affinity to force related workloads to run on the same node, minimizing network latency for high-performance communication.
Why Colocate Workloads?
In previous lessons, we discussed how to distribute pods across different nodes for high availability using anti-affinity. However, sometimes the opposite is true. If you have a web application pod and a caching pod (like Redis) that communicate thousands of times per second, the network travel between two different physical nodes can introduce latency. By "colocating" these pods on the same node, they can communicate over the local loopback interface or a much faster internal bus, significantly boosting performance.
Implementing Pod Affinity
To tell Kubernetes that a pod wants to live near another, we use the podAffinity block within the affinity specification of your Pod or Deployment manifest. We define a labelSelector to identify the "anchor" pod and a topologyKey to define the boundary (usually kubernetes.io/hostname for the same node).
Here is an example of a web application pod configured to sit on the same node as a backend-cache pod:
spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- backend-cache
topologyKey: "kubernetes.io/hostname"
How It Works
When you deploy this configuration, the Kubernetes scheduler checks the cluster for existing pods labeled app: backend-cache. It will only schedule the new web pod onto a node that is already running that cache pod.
If you use requiredDuringSchedulingIgnoredDuringExecution, the pod will refuse to schedule if no such node is available. Alternatively, you can use preferredDuringSchedulingIgnoredDuringExecution if you want to keep them together when possible, but allow the pod to run elsewhere if the cluster is under heavy pressure. This fine-grained control ensures your latency-sensitive components stay physically close, keeping your distributed system snappy and efficient.
Key Takeaway: Use Pod Affinity to ensure high-bandwidth, latency-sensitive microservices are colocated on the same node to optimize internal network performance.