Pod affinity and anti-affinity in Kubernetes - Time & Space Complexity
When Kubernetes schedules pods, it checks rules like pod affinity and anti-affinity to decide where pods should run.
We want to understand how the time to make these decisions grows as the number of pods and nodes increases.
Analyze the time complexity of this pod scheduling snippet with affinity rules.
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: security
operator: In
values:
- S1
topologyKey: kubernetes.io/hostname
containers:
- name: nginx
image: nginx
This pod requests to be scheduled on a node where pods with label "security: S1" already run on the same hostname.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking all existing pods on all nodes to find matches for affinity rules.
- How many times: For each node, the scheduler scans pods running there to verify label matches.
As the number of nodes and pods grows, the scheduler must check more pods per node to satisfy affinity rules.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 nodes, 50 pods | Checks pods on each node, about 50 checks total |
| 100 nodes, 500 pods | Checks increase roughly 10 times, about 500 checks |
| 1000 nodes, 5000 pods | Checks increase roughly 100 times, about 5000 checks |
Pattern observation: The number of checks grows roughly linearly with the total number of pods across nodes.
Time Complexity: O(n)
This means the scheduling time grows roughly in direct proportion to the number of pods the scheduler must check for affinity.
[X] Wrong: "The scheduler only checks one node or a fixed small number of pods regardless of cluster size."
[OK] Correct: The scheduler must evaluate all nodes and pods to find a suitable place, so the work grows with cluster size.
Understanding how pod affinity affects scheduling time helps you explain real cluster behavior and scalability in interviews.
What if we changed requiredDuringSchedulingIgnoredDuringExecution to preferredDuringSchedulingIgnoredDuringExecution? How would the time complexity change?
Practice
podAffinity in Kubernetes?Solution
Step 1: Understand podAffinity concept
Pod affinity is used to place pods close to other pods that have specific labels, improving communication or resource sharing.Step 2: Compare options with podAffinity purpose
Only To schedule pods close to other pods with matching labels describes placing pods close to others with matching labels, which matches podAffinity's goal.Final Answer:
To schedule pods close to other pods with matching labels -> Option DQuick Check:
podAffinity = place pods close [OK]
- Confusing affinity with anti-affinity
- Thinking affinity limits pods per node
- Mixing affinity with pod restart policies
Solution
Step 1: Identify required pod anti-affinity syntax
Required pod anti-affinity usespodAntiAffinitywithrequiredDuringSchedulingIgnoredDuringExecutionand a label selector plus topology key.Step 2: Match syntax with options
"podAntiAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": [{"labelSelector": {"matchLabels": {"app": "web"}}, "topologyKey": "kubernetes.io/hostname"}]} correctly usespodAntiAffinitywithrequiredDuringSchedulingIgnoredDuringExecutionand proper labelSelector and topologyKey.Final Answer:
Correct required pod anti-affinity syntax -> Option AQuick Check:
Required anti-affinity uses podAntiAffinity + requiredDuringScheduling [OK]
- Using podAffinity instead of podAntiAffinity
- Confusing required and preferred rules
- Wrong topologyKey values
app: frontend is scheduled?affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: backend
topologyKey: kubernetes.io/hostnameSolution
Step 1: Understand required podAffinity behavior
Required podAffinity means the pod must be placed on a node where pods with matching labels already run, here app=backend.Step 2: Apply to given pod spec
The pod with label app=frontend requires a node with pods labeled app=backend, so it will schedule only on such nodes.Final Answer:
The pod will be scheduled on a node that already runs a pod with label app=backend -> Option CQuick Check:
Required podAffinity = schedule near matching pods [OK]
- Thinking podAffinity prevents scheduling near pods
- Confusing required and preferred affinity
- Assuming scheduling fails without matching pods
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: database
topologyKey: ""
What is the likely cause?
Solution
Step 1: Check topologyKey usage
ThetopologyKeymust be a valid node label key likekubernetes.io/hostname. Empty string disables the rule.Step 2: Understand scheduler behavior
With emptytopologyKey, the scheduler ignores the anti-affinity rule, allowing pods on same node.Final Answer:
Empty topologyKey causes the rule to be ignored -> Option AQuick Check:
Valid topologyKey needed for anti-affinity [OK]
- Leaving topologyKey empty
- Misplacing anti-affinity under preferred instead of required
- Assuming required rules are ignored
app: cache so that no two pods run on the same node, but you want the scheduler to try to keep pods in the same zone if possible. Which affinity configuration achieves this?Solution
Step 1: Prevent pods on same node strictly
UsepodAntiAffinitywithrequiredDuringSchedulingIgnoredDuringExecutionandtopologyKey: kubernetes.io/hostnameto ensure no two pods run on the same node.Step 2: Prefer pods in same zone
AddpodAffinitywithpreferredDuringSchedulingIgnoredDuringExecutionandtopologyKey: failure-domain.beta.kubernetes.io/zoneto encourage scheduling pods in the same zone but not strictly.Step 3: Combine both rules
UsepodAntiAffinitywithrequiredDuringSchedulingIgnoredDuringExecutiononapp: cacheandtopologyKey: kubernetes.io/hostname, pluspodAffinitywithpreferredDuringSchedulingIgnoredDuringExecutionontopologyKey: failure-domain.beta.kubernetes.io/zonecombines strict anti-affinity on node and preferred affinity on zone, matching the requirement.Final Answer:
Use required podAntiAffinity on hostname and preferred podAffinity on zone -> Option BQuick Check:
Strict anti-affinity + preferred affinity = UsepodAntiAffinitywithrequiredDuringSchedulingIgnoredDuringExecutiononapp: cacheandtopologyKey: kubernetes.io/hostname, pluspodAffinitywithpreferredDuringSchedulingIgnoredDuringExecutionontopologyKey: failure-domain.beta.kubernetes.io/zone[OK]
- Using affinity instead of anti-affinity to separate pods
- Using preferred instead of required for strict separation
- Ignoring zone preference
Ready to prove it?
Pass the test and this pattern moves unknown
