cloudnative-pg icon indicating copy to clipboard operation
cloudnative-pg copied to clipboard

[Feature]: Scheduling constraints applied only to the primary instance Pod

Open BoxBoxJason opened this issue 2 months ago • 1 comments

Is there an existing issue already for this feature request/idea?

  • [x] I have searched for an existing issue, and could not find anything. I believe this is a new feature request to be evaluated.

There is no feature request for this, but the need has come up several times in Q&A discussions, none of which led to an issue:

  • #3985: "How to specify nodes for Primary Pod and replicas using Pod Affinity?" (includes a request for primary on on-demand nodes, replicas on spot nodes)
  • #9465: "Prefer node with specific label for primary"
  • #1278: "Volume for a Unix Socket and primary affinity scheduling" (point 2: affinity for the primary only)
  • #4369: "Disperse Primary Pods equally across Kubernetes Compute Nodes" (closed as stale, not rejected)

What problem is this feature going to solve? Why should it be added?

We run applications on the same Kubernetes cluster as their CNPG database, and we want each application to run on the same node as the primary it writes to, to keep network latency between them low. We have "considerably slower" traffic between nodes because our CNI ciphers inter node traffic (there is no service mesh enabled).

Our setup today:

  • 3 instances per Cluster, with podAntiAffinityType: required: we never want two instances on the same node.
  • The application Pods have a pod affinity towards the primary, using the cnpg.io/instanceRole: primary label, so when an application Pod restarts it goes to the primary's node.

What breaks: when the primary Pod is recreated without a switchover (which happens regularly for us after a node failure or a network issue on the node, the database wal pvc gets full, the primary pod enters crashloopbackoff, we have to manually increase the PVC and restart the primary) the operator recreates the Pod of the same instance, and the scheduler places it on any node that satisfies the cluster-wide rules. Nothing attracts it back to the application, so the locality is lost until the application crashes / restarts / gets updated...

We cannot express this with the existing fields, because every rule in .spec.affinity and .spec.topologySpreadConstraints applies to all the instances:

  • a required pod affinity towards the application would conflict with the required anti-affinity between instances (only one instance fits on the application's node), leaving the other instances Pending;
  • a preferred pod affinity attracts every instance, so a replica that is recreated first can take the application's node, and the primary can then no longer go there.

What we need is to attract only the primary towards the application, while the replicas keep following the cluster-wide rules, and should also be repealed by the application

Describe the solution you'd like

API declaration

An optional field in the Cluster spec, holding scheduling constraints that are added only to the Pod of the primary instance:

spec:
  instances: 3
  affinity:
    podAntiAffinityType: required
  primaryScheduling:
    podAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          labelSelector:
            matchLabels:
              app: my-app
          topologyKey: kubernetes.io/hostname

primaryScheduling would accept nodeAffinity, podAffinity, podAntiAffinity and topologySpreadConstraints, using the standard Kubernetes types, so users choose between preferred and required rules as they do elsewhere.

Proposed semantics, chosen so that the feature never gets in the way of high availability:

  1. Additive. The terms are merged with those generated from .spec.affinity and .spec.topologySpreadConstraints; they never replace them. Required node affinity terms are combined so that a node must satisfy both the cluster-wide and the primary terms (node selector terms are ORed by Kubernetes, so plain appending would loosen the constraint).
  2. Scheduling time only. The constraints are added to the Pod of the instance that is status.targetPrimary when the operator creates it: the first primary at bootstrap, or the primary's Pod when it is recreated.
  3. No influence on the election. Failover and switchover keep choosing the instance exactly as today. After a role change, no Pod is restarted or moved because of these constraints (they are only meaningful at scheduling time, like any IgnoredDuringExecution rule). This keeps the principle that every instance can become primary.
  4. Unsatisfiable constraints cannot block the cluster. If the primary's Pod stays Pending because of required rules, the usual failover promotes another instance; the Pending Pod is then recreated as a replica, without the primary constraints, through the existing unschedulable-Pod handling.
  5. Rollouts. Setting the field for the first time does not restart anything; it takes effect the next time the primary's Pod is created. Changing it rolls out the Pods that were created with the previous constraints, like a change to .spec.affinity does today.

Further evolutions

Out of scope for a first iteration, but a possible follow-up: using these constraints as a tie-breaker when choosing the switchover/failover candidate, or switching over to an instance that satisfies them. I deliberately left this out because it touches the election logic.

A symmetric replicaScheduling field (constraints added only to replica Pods) is another possible extension, and the primaryScheduling name leaves room for it without renaming anything. I am not asking for it now:

  • In our setup, replicas should stay away from the application's node so that the primary can be scheduled there. With primaryScheduling, this can be expressed with preferred rules: a cluster-wide additionalPodAntiAffinity towards the application (e.g. weight 50) plus a stronger primaryScheduling.podAffinity towards it (e.g. weight 100). The replicas score negatively on the application's node, while the primary still scores positively there.
  • A required replica rule would only help when a replica Pod is created. The most common way a replica ends up next to the application is a failover, where the old primary is demoted in place, and no scheduling rule changes that.
  • A required anti-affinity between replicas and the application can leave replicas Pending when the application runs on many nodes, which reduces availability.

If the preferred rules turn out not to be enough in practice, I will come back with data for a separate proposal.

I have a working implementation of the above on a branch of my fork (API field, Pod generation, PodSpec drift handling, unit tests, documentation) and I am happy to open a PR if the maintainers agree with the approach, or to change it based on feedback: (waiting for approval / assignment to publish it)

Describe alternatives you've considered

  • Cluster-wide additionalPodAffinity: applies to every instance; see the problem statement for why neither preferred nor required rules work with one instance per node.
  • cnpg.io/podPatch annotation: the patch is applied to every instance Pod, so it cannot target only the primary.
  • Only making the application follow the primary (what we do today): the application's pod affinity is IgnoredDuringExecution, so when the primary's Pod moves, the already running application Pods stay where they are. Restarting the application every time the primary moves is the operation we want to avoid.
  • Periodically running kubectl cnpg promote towards the instance on the application's node: it requires an instance to already be on that node, and it means repeated switchovers (with write downtime) driven by external automation.
  • A mutating admission policy (Kyverno or similar) on Pod creation, reading status.targetPrimary from the Cluster: this should work in principle, because the operator stores the PodSpec before admission, but it adds an external policy engine to the critical path and depends on internal status fields. It also cannot clean up a Pod left Pending by required rules after a failover.
  • A CNPG-I plugin using the lifecycle hook: the operator also runs the hook to compute the expected PodSpec, so role-dependent output would make the plugin trigger rollouts after every switchover unless it reimplements the drift handling.

Additional context

AI disclosure, as per the AI contribution policy: I used Claude (Claude Code, Claude Opus 5.5) to search the existing issues and discussions, to review the operator code paths involved (Pod generation in pkg/specs/pods.go, Pod recreation in findInstancePodToCreate, PodSpec drift detection in checkPodSpecIsOutdated, and processUnschedulableInstances), and to draft the implementation on my branch. I have reviewed the design and the code and I take responsibility for them; any PR will carry the Assisted-by: trailer.

I will be running tests to ensure the "required" scheduling mode doesn't interfere with primary election if this feature is accepted. We should only consider "preferred" mode if it does.

Backport?

No

Are you willing to actively contribute to this feature?

Yes

Code of Conduct

  • [x] I agree to follow this project's Code of Conduct

BoxBoxJason avatar Oct 02 '26 19:10 BoxBoxJason

I disagree with "No influence on the election."

Switching primary is quite transparent, fast and (should) not break the application.

Hence, I think is a better idea to have the primary election prefers to be in the same node than the application is running.

Could be a good feat for a v2 🚀

ebuildy avatar Oct 03 '26 12:10 ebuildy