Sub topic 3
Writing a topology spread constraint
This chapter assumes you can write Deployments, use labels and selectors, and run kubectl apply. It also assumes you know that nodes carry labels such as topology.kubernetes.io/zone. Here you will write a constraint and learn what each field does. The next chapter covers the skew arithmetic in detail.
Where the constraint goes
A topology spread constraint is a list under spec.topologySpreadConstraints in the pod spec. In a Deployment, that is spec.template.spec, not the Deployment's own spec. The scheduler reads it each time it places a pod that carries the constraint.
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 6
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: web
containers:
- name: web
image: nginx:1.27The four core fields
| Field | Meaning |
|---|---|
| `topologyKey` | The node label that defines a domain. Nodes with the same value for this label belong to one domain. |
| `maxSkew` | The largest allowed difference in matching pod count between any two domains. It must be greater than zero. |
| `whenUnsatisfiable` | What the scheduler does if placing the pod would break `maxSkew`. `DoNotSchedule` leaves the pod Pending. `ScheduleAnyway` places it and prefers the least-skewed option. |
| `labelSelector` | Which pods are counted when comparing domains. |
The selector counts pods, it does not select them
The labelSelector does not choose which pods the constraint applies to. The constraint applies to the pod that declares it. The selector only decides which existing pods are counted in each domain. In nearly every case it should match the pod's own labels, as app: web does above. If it matches nothing, every domain counts zero and the constraint has no effect. Counting is limited to the pod's namespace.
Common errors
- Placing the block at the wrong level. In a Deployment it must sit inside
spec.template.spec. - Using a
topologyKeythat nodes lack. Nodes without that label are not part of any domain. The scheduler won't place the pod on them underDoNotSchedule. Check withkubectl get nodes -L topology.kubernetes.io/zone. - A selector that does not match the pod's labels. The constraint then silently counts the wrong pods.
- Expecting existing pods to move. Constraints are evaluated only when a pod is scheduled.
Exercise
A Deployment's pods carry the label app: api, but its constraint uses labelSelector: {matchLabels: {app: web}}. What happens to the spread?
Show answer
The selector matches no pods, so every domain counts zero and the skew is always within limits. The constraint has no practical effect. Fix the selector to match app: api.