# Add Topology Spread Constraints to Kubernetes Deployments

Yes. An agent reads every Deployment in your manifests, adds topologySpreadConstraints across zones and nodes, and proves the output still builds and validates.

[Run this on Rush](https://cloud.getrush.ai/run/add-topology-spread-constraints/kubernetes/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the repository produces its manifests before it edits any of them. In a repository like GoogleCloudPlatform/microservices-demo there are three copies of the same Deployments: plain files in `kubernetes-manifests/`, a Kustomize base in `kustomize/base/` listed by its `kustomization.yaml`, and a Helm chart in `helm-chart/`. The agent reads `.github/workflows/kustomize-build-ci.yaml`, which runs `kubectl kustomize .` on `kustomize/` and `kustomize build` on each folder under `kustomize/tests/`, and `docs/releasing/README.md`, which says the release workflow regenerates manifests, so it edits the sources developers maintain and leaves the generated `release/` files alone unless the prompt asks for them.

Then it reads each Deployment to see what is already there. `kubernetes-manifests/frontend.yaml` and `cartservice.yaml` set a pod `securityContext`, drop all capabilities, declare readiness and liveness probes and give `cartservice` requests of `200m` CPU and `64Mi` memory, but none of the ten service Deployments sets `affinity`, `topologySpreadConstraints` or even `replicas`; only `loadgenerator.yaml` sets `replicas: 1`. Each pod template carries a single `app: <service>` label, which is what the constraint's `labelSelector` has to match.

For each Deployment it adds two constraints under `spec.template.spec`: one with `topologyKey: topology.kubernetes.io/zone` and one with `topologyKey: kubernetes.io/hostname`, both with `maxSkew: 1` and a `labelSelector` on that Deployment's own `app` label. The zone constraint uses `whenUnsatisfiable: ScheduleAnyway` so a single-zone cluster still schedules, and the hostname constraint uses `DoNotSchedule` only when the prompt asks for a hard rule. In the Helm chart it adds the same block to each service template behind a values flag so existing installs keep their current behaviour until it is enabled. It applies the same edit to the Kustomize base and the plain manifests so the three copies stay in step.

Before pushing, it runs `kubectl kustomize kustomize/` and `kustomize build` for every folder in `kustomize/tests/`, the same commands the CI workflow runs, then `helm template helm-chart/` and `helm lint`, and validates the rendered YAML with `kubeconform`. It opens the pull request, reads the kustomize-build and helm-chart workflow runs on it, and fixes anything that fails. The pull request description notes that constraints only move pods once a Deployment has more than one replica, since these manifests leave `replicas` at its default.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add topologySpreadConstraints to every Deployment in this repository. Read how manifests are produced first (plain YAML, Kustomize bases and components, Helm templates) and edit the sources, not generated release files. For each Deployment add a zone constraint on topology.kubernetes.io/zone with maxSkew 1 and whenUnsatisfiable ScheduleAnyway, and a node constraint on kubernetes.io/hostname with maxSkew 1, each with a labelSelector matching that Deployment's own pod labels. In the Helm chart put the block behind a values flag that defaults to off. Render everything with kubectl kustomize, kustomize build for every test overlay, helm template and helm lint, and validate the output with kubeconform before you push. Open a pull request and make sure its checks pass; if one fails, fix it and push again.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on a new branch that touches each Deployment in `kubernetes-manifests/`, each file in `kustomize/base/`, and each service template plus `values.yaml` in `helm-chart/`. In a repository shaped like microservices-demo that is the ten service Deployments and the load generator, each gaining a `topologySpreadConstraints` list whose `labelSelector` matches its own `app` label, and a Helm value that turns the block on. The description lists every Deployment changed, the topology keys used, and which constraint is soft and which is hard.

The proof is the repository's own checks running on the pull request: the kustomize-build workflow renders the base and every test overlay, and the Helm chart workflow lints and templates the chart. The session keeps every `kubectl kustomize`, `helm template` and `kubeconform` command the agent ran with its full output, so a reviewer can see the rendered constraint for any service without checking the branch out.

Before merging, a reviewer checks that the cluster's nodes actually carry `topology.kubernetes.io/zone` labels, that `maxSkew: 1` across zones fits how many replicas each service will run, and that a hard hostname constraint does not block scheduling on a small cluster. They also decide whether to raise `replicas` in the same change, because spreading a single pod changes nothing until there is a second one.

## Run it on every new Deployment added to the repository

Add an automation in the Project with this prompt and a `github` trigger on `pull_request.opened` and `pull_request.synchronize` on `main`, scoped by the prompt to Deployments the pull request adds or changes. The trigger adds the pull request event after the prompt, so the agent reads which manifests changed and adds constraints only there, as a review or a follow-up commit on its own branch depending on what you ask for. Only pull requests by owners, members and collaborators start a run.

For repositories that already exist, have a script or your server send this same request once per repository with its URL in `resources`, with a fresh UUID as `request_id` so a retried request returns the run already started. Each run has its own sandbox and its own pull request, and Rush POSTs `run.completed` or `run.failed` to the webhook URL set on the key when each run's turn ends.

## Why run it on Rush?

Editing eleven Deployments in three formats by hand is tedious and easy to get subtly wrong: a `labelSelector` that copies the previous service's label spreads nothing and errors nowhere. On Rush the agent edits all three copies in its own sandbox, then renders them with the exact commands the repository's CI runs and validates the output with `kubeconform` before the first push, so the pull request arrives already green rather than after three rounds of fixes from your laptop.

The result carries its own proof. The repository's kustomize and Helm workflows run on the agent's pull request, and the trajectory holds every render and validation command with its output, so a reviewer can read the constraint as rendered for `cartservice` without cloning the branch. The same request can run against every manifest repository in the organization at once, each run isolated and each change behind a pull request a person approves.

## Frequently asked questions

### Will it edit the generated release manifests too?

Not unless you ask. The agent reads `docs/releasing/README.md` and sees the release workflow regenerates `release/kubernetes-manifests.yaml`, so it edits the plain manifests, the Kustomize base and the Helm chart, which are the sources. If your repository has no such generation step and the release file is hand-maintained, say so in the prompt and it edits that file as well.

### My Deployments have no replicas set. Is the constraint still useful?

It is harmless and ready, but it changes nothing until a Deployment has at least two pods, because there is nothing to spread. The pull request description says this plainly. Add `replicas` or an autoscaler in the same prompt if you want the change to take effect immediately, and the agent will include it.

### Will a hard constraint stop my pods from scheduling on a small cluster?

It can. With `whenUnsatisfiable: DoNotSchedule` on `kubernetes.io/hostname` and `maxSkew: 1`, a third replica on a two-node cluster stays pending. That is why the default here is a soft zone constraint and the hard hostname constraint is opt-in, and why the pull request names the choice so a reviewer can flip it for their cluster.

### How does it keep the Kustomize, Helm and plain manifests consistent?

It applies the same block to each copy and then renders all three, comparing the `topologySpreadConstraints` section of the rendered output per service. The Helm copy is behind a values flag so an existing release is unchanged until the flag is set. Any copy that renders differently from the others is fixed before the agent pushes.

## More Kubernetes jobs

- [Add Vertical Pod Autoscaler Recommendations to Kubernetes Deployments](https://getrush.ai/run/add-vertical-pod-autoscaler/kubernetes/)
- [Make Kubernetes Manifests Pass the Restricted Pod Security Standard](https://getrush.ai/run/enforce-pod-security-restricted/kubernetes/)
- [Fix the Cause of a Grafana Alert in Kubernetes](https://getrush.ai/run/fix-grafana-alerts/kubernetes/)

## More jobs like this: Hand off a long task

- [Add towncrier Changelog Fragments to a Python Package](https://getrush.ai/run/add-towncrier-changelog/python/)
- [Wrap Multi-Step Writes in GORM Transactions](https://getrush.ai/run/add-transactions/gorm/)
- [Add Transactions to a Prisma App](https://getrush.ai/run/add-transactions/prisma/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
