👯 Keep Related Pods Close (or Far Apart)
Cache and app should be on same node. Database replicas should be on different nodes. Pod affinity/anti-affinity controls pod placement.
📝 Pod Affinity (Same Node)
apiVersion: v1
kind: Pod
metadata:
name: web-app
spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: cache
topologyKey: kubernetes.io/hostname
containers:
- name: app
image: myapp
# Web pod will be scheduled on same node as cache pod
🚫 Pod Anti-Affinity (Different Nodes)
apiVersion: apps/v1
kind: Deployment
metadata:
name: database
spec:
replicas: 3
template:
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: database
topologyKey: kubernetes.io/hostname
containers:
- name: db
image: postgres
# Database replicas will NEVER be on same node (high availability)
✅ Preferred (Best Effort) vs Required (Hard Constraint)
- requiredDuringScheduling: Must satisfy (hard constraint)
- preferredDuringScheduling: Try to satisfy (soft constraint)
- Use ‘preferred’ for performance optimization
- Use ‘required’ for security/compliance
“Redis cache and app on different nodes = slow. Added podAffinity: same node. Latency dropped 80%. Kubernetes affinity is underrated.”
