Sobes.tech
Middle

How to evenly distribute pods across availability zones?

sobes.tech AI

Answer from AI

Use topologySpreadConstraints in the pod or deployment manifest.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 9
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app-container
        image: my-app:latest
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone # Key that defines the spread domain (availability zone)
        whenUnsatisfiable: DoNotSchedule # If distribution is impossible, the pod will not be scheduled
        labelSelector:
          matchLabels:
            app: my-app # Constraint applies to pods with this label

maxSkew defines the maximum number of pods that can exceed the average number of pods in any topology domain (availability zone). In this case, maxSkew: 1 means the difference in the number of pods between any two zones will not exceed 1.

topologyKey: topology.kubernetes.io/zone indicates that the distribution should be based on node zone labels.

whenUnsatisfiable: DoNotSchedule means that if the scheduler cannot satisfy the topologySpreadConstraints, the pod will not be scheduled. Another option is ScheduleAnyway, which will attempt to schedule the pod but may violate the constraint.

labelSelector defines the set of pods to which this constraint applies.

For even distribution of pods across three zones (e.g., us-east-1a, us-east-1b, us-east-1c) with 9 replicas, each zone will get 3 pods.

This distribution increases application fault tolerance, as a failure of one availability zone will not lead to complete service unavailability.