Sub topic 4
Working out skew by hand
This chapter assumes you can read a Deployment manifest, know that nodes carry labels such as topology.kubernetes.io/zone, and have seen the fields of a topologySpreadConstraints block. Here you learn to calculate skew yourself, so you can predict where the scheduler will place the next pod.
The skew formula
A topology domain is one value of the topology key. With the key topology.kubernetes.io/zone, the zones a, b and c are three domains.
The scheduler counts the pods that match the constraint's labelSelector in each domain. It then computes skew for the domain where it is considering a placement:
skew = (matching pods in that domain, after placing the new pod) - (matching pods in the domain with the fewest)The placement is allowed if skew is at most maxSkew. The minimum is taken over all eligible domains, including domains that currently hold zero matching pods.
A worked example
Take maxSkew: 1, the zone key, and a Deployment that has already placed five pods:
| Zone | Matching pods now |
|---|---|
| a | 2 |
| b | 2 |
| c | 1 |
The minimum is 1, in zone c. Now test each zone for the sixth pod:
| Candidate zone | Count after placing | Minimum | Skew | Allowed (maxSkew 1)? |
|---|---|---|---|---|
| a | 3 | 1 | 2 | No |
| b | 3 | 1 | 2 | No |
| c | 2 | 1 | 1 | Yes |
Only zone c passes, so the pod goes there. The result is 2, 2, 2. The seventh pod then passes in any zone, because every placement gives a skew of 1.
Empty domains matter
Suppose zone c has no eligible node, or no pod yet. If three zones exist and the counts are 1, 1, 0, the minimum is 0. A new pod in zone a would give a count of 2 and a skew of 2, so it is rejected. This is why the first few replicas of a Deployment spread out so evenly.
Common mistakes
- Counting all pods. Only pods that match the
labelSelectorcount. Pods from other apps in the same zone are ignored. - Forgetting the new pod. Skew is measured after the placement, not before.
- Ignoring domains that have no pods. A zone with zero matching pods is the minimum, so it raises skew everywhere else.
- Expecting a perfect balance. With
maxSkew: 2, counts of 4, 3 and 2 are legal. Larger values trade balance for scheduling freedom.
Exercise
A constraint uses maxSkew: 1 on the zone key. Zones a, b and c hold 3, 2 and 2 matching pods. Which zones can accept the next pod, and why?
Show answer
Zones b and c can. The minimum is 2. Placing in a gives 4 - 2 = 2, which exceeds maxSkew 1. Placing in b or c gives 3 - 2 = 1, which is allowed.
Exercise
Zones a and b hold 2 and 2 matching pods, and zone c is eligible but empty. With maxSkew 1, can the next pod go in zone a?
Show answer
No. The minimum is 0, because empty eligible domains count. Placing in a gives 3 - 0 = 3, which exceeds maxSkew 1. Only zone c passes, with 1 - 0 = 1.