Repository navigation
Replies: 19 comments 15 replies
|
Hello @NikolayS! 👋 I'm here to help you with bugs, answer questions, and guide you on your journey to becoming a contributor. While you wait for a human maintainer, feel free to ask me anything! A similar issue was previously discussed and closed. The proposed solution involved changes to the failover mechanism in case of synchronous replication. It suggested promoting a replica only if it can be determined to contain the last commit of the primary, requiring all replicas that were available at the moment the primary disappeared to be available for inspection. If this cannot be determined, or if there were no synchronous standbys, there should be no failover until either the primary comes back, the required replica(s) come back, or the DBA manually promotes a replica. This approach aims to prevent data loss by ensuring that only up-to-date replicas are promoted [1]. To address the split-brain issue, the CloudNativePG operator uses For further prevention of split-brain scenarios, configuring anti-affinity rules is recommended. This includes enabling pod anti-affinity, using topology keys to distribute instances across nodes, and setting strict anti-affinity types. Additionally, using node selectors and tolerations can help ensure that PostgreSQL instances are distributed across different nodes, reducing the risk of split-brain scenarios [4][5][6][7]. To continue talking to Dosu, mention @dosu. Help Dosu learn! Give it feedback: Great Response | Irrelevant Answer | Incorrect Sources | Too Verbose | Hallucination | Bug Report | Other |
|
AI is great, but answers provided by the bot are not fully relevant, my questions remain. |
|
I wasn't aware that CloudNativePG relies entirely on participating quorum to maintain cluster state. From the perspective of the operator, any Primary node that loses quorum beyond the failover threshold should self-terminate or minimally cease service endpoint availability. This is something even repmgr can be configured to do, so it seems odd to be absent from CNPG. |
|
Additional consideration: forget about local workloads (such as initiated by pg_cron); the problem is bigger; anti-affinity won't help. Imagine we have 3 nodes, each one is in its own AZ. The AZ, where the primary is located, gets network issues, disconnected. All application nodes running in that AZ, even with anti-affinity with respect to the old primary, will continue talking to that old primary, and opening new connections will continue working because kube-proxy doesn't update iptables there. In other AZs, we'll already have a new primary and app nodes there will speak to it. |
|
will k8s itself use services to stop directing traffic to anything running on the node? so even if some application pod is running on the same node as a PG instance loses network connectivity to the k8s control plane, k8s should stop directing any traffic to that application pod. this may provide the same reduction of data loss risk around split brain as what patroni has with watchdog and pg_rewind [even patroni can lose up to 10 seconds of data in a split brain with automated rewind right?] also, following the recommended config of three node clusters and quorum based sync replication (with furthermore if you're using the recommended config of a k8s topology key that matches AZs on a cloud-provided managed k8s service, then you're guaranteed that the quorum based sync always crosses two data centers. in this configuration it seems there would be almost no risk of a writer continuing to accept writes in a split brain situation. it is an interesting question if we should have an extra level of robustness by coding the CNPG instance manager to kill itself if it know that contact with the k8s control plane is lost? |
|
Hi @NikolayS, Thank you for taking the time to evaluate CloudNativePG, open this issue, and clearly describe your use case and expectations by providing a reproducible test case. I apologise for the delay in our response. Last week, many of us were on holiday, and the rest were fully engaged with the 1.26 release, following a busy and successful Kubecon for the project. I'm also responding for the other maintainers. We have debated this issue for a long time, even before CloudNativePG was open-sourced, and we have decided not to implement anything that would automatically fence an isolated primary, at least for now. Let me explain our reasoning. At the heart of this situation is a fundamental trade-off dictated by the CAP theorem. In the case of a network partition, all architectural choices must ultimately compromise either consistency or availability. For optimal consistency, we have always recommended the following:
If availability is prioritised (thus not considering synchronous replication), users accept the potential for data loss, as the goal is to provide a new primary to applications as quickly as possible. Data loss scenarios are comparable to those in traditional PostgreSQL environments and may involve the challenging recovery of certain data portions from a physical backup. The example you presented falls into this category. Since both the workload and the target PostgreSQL node are in the same isolated partition, their side effects are not visible outside that partition. When the partition reconnects, WAL files are correctly archived, and everything is rolled back. Only the workloads inside the isolated partition may become aware of the transaction effects. This outcome is similar to that of an automated failover when all replicas are lagging, and business priorities favour Recovery Time Objective (RTO) over Recovery Point Objective (RPO). We have also implemented further precautions, such as a failover delay and, from version 1.26, a readiness probe strategy for replicas. I hope these explanations clarify why automated fencing of an isolated primary has not yet been implemented in CloudNativePG. We believe that the above recommendations can already address your example and meet the consistency requirements in production. If that is not the case, we are open to collaborating with the CloudNativePG community on a new feature that mitigates this scenario. For instance, we have considered a system that shuts down a PostgreSQL primary when it is isolated from the API server and other replicas. Thank you once again for helping us improve CloudNativePG. Your feedback is really appreciated. |
|
Given Gabriele's explanation, I have to note that the Patroni-based operators do not suffer from the issue highlighted by Nikolay, regardless of your specific Kubernetes deployment topology. A node without the leadership key is automatically unroutable due to the REST interface, and Patroni goes a step further and stops the Postgres service until it can re-establish consensus for the rewind. You could have a two node cluster and still be protected, provided the consensus layer is working properly. The Postgres node deployment strategy is not relevant to maintaining proper node isolation; it must be inherent in the design or it may as well not exist at all. |
|
Hi Shaun.
That's true, but unfortunately, kube-proxy won't change the iptables rules when the node can't reach the API server.
That mitigates the issue. Until the leader lock expires, the old primary is still active. Depending on how the system is set up, those transactions may be lost. I like that feature, and I’m in favour of having some mitigation in CNPG, like what Gabriele said previously on our behalf. However, I confirm our position that synchronous replication is the best option for consistency purposes. Leonardo |
|
Hi Shaun,
Could you please help me better understand this by providing more details? Thanks, |
Let's see if I can clarify that. The repmgr service has a few settings: child_nodes_connected_min_count = 1
child_nodes_disconnect_min_count = 1
child_nodes_disconnect_command = '/some/fencing/script.sh'I don't particularly like this implementation because none of these hook scripts are included, and it's easy to get wrong. But the point is that the daemon will detect when it has been isolated from the rest of the quorum, realize it will be outvoted, and take some corrective action. This would be a minimal configuration of repmgr IMO, as it establishes an inescapable architecture that self-enforces a quorum requirement regardless of how you organize your Postgres nodes. Similarly, the pg_auto_failover system relies on a monitor service on a separate node to handle cluster management. I don't like this design because it's incredibly fragile and the monitor node acts as a SPOF for automated failovers. Regardless, the ideal design would be two Postgres nodes and a monitor node. If the Primary loses contact with the monitor, it knows it's been cut off from the quorum and will self-fence. This is part of the state machine in their documentation. Patroni essentially goes one step further than both of these and presents a two-layer model. The consensus layer is required for any operation, and losing contact with it means automatic shutdown and relinquishing the leadership key. This includes any situation where the consensus layer itself cannot establish a majority in the event of a partition. The REST interface provided by Patroni controls all routing (or it should in a properly configured system), so a node without the leadership key would lose routing within the health check timeout. So if your Postgres / Patroni node loses contact with a majority of the consensus layer, Postgres on any affected node is shut down. Assuming the routing layer is monitoring either the consensus key or the Patroni REST interface, it should also remove routing. In a Kubernetes context, any colocated applications would be unable to communicate with them because either the service endpoints would be terminated, or because Postgres itself is stopped. It's part of the design. So long as the stack is operating at all, you can't override the built-in resilience to Split Brain. I don't have to build some sophisticated series of node affinities and application distributions, or rely on synchronous replication; it just works as advertised because it has no choice but to do so. To rely on synchronous replication to "fix" this for you means every single cluster needs a minimum of three nodes to impose an implied transaction quorum. If you set I had wrongly assumed that CloudNativePG was effectively doing the same thing as Patroni, but cutting out the middle man. The operator has direct access to the consensus layer, and it knows the state of the full cluster at any time. Upon cluster state change such as a key expiration event, timeout, or lost consensus, I assumed it did the same thing: stopping ingress services and either terminating affected pods, or some other equivalent. Maybe I shouldn't have assumed this, but it seemed a natural conclusion given Patroni has long been considered the modern approach for the last 10 years or so due to the inherent built-in safety of its design, compared to something less robust like repmgr or EFM. Now that I know this, I will make it policy to advise anyone using CNPG to always deploy with 3 nodes set to sync-rep, and exactly why that's the case. Until such a time it adds an inherent and inescapable fencing protocol, I don't consider it a modern HA solution. |
|
@gbartolini thank you for response. Why don't you use Patroni or follow the same path?
Here is an example showing really well that sync rep is not a full solution: https://www.postgresql.org/message-id/flat/C1F7905E-5DB2-497D-ABCC-E14D4DEE506C%40yandex-team.ru |
What happened to this consideration? |
|
Hi Nikolay and Shaun, TL;DR: After version 1.26.0, I believe we should evaluate submitting a draft pull request with a proposed solution in CNPG on the same path as Patroni, allowing us to receive early feedback and potentially include the feature in version 1.27. Thank you for the information you provided. Shaun: Yes, we knew the idea behind Patroni’s failsafe. I fully support implementing a configurable failsafe approach for an isolated primary in CloudNativePG’s instance manager. Therefore, I am converting this issue into a discussion to gather ideas for a new feature to be included in a future release of CloudNativePG, starting with ours (below), to Nikolay’s point. There are several possible implementations we’ve considered over time, all of which aim to enhance the instance manager by facilitating the shutdown of a primary in a multi-instance cluster under the following conditions (they must happen all at the same time):
Roughly, the last two points would allow Postgres to keep functioning when the problem is limited to the API server connection (the equivalent of Patroni’s DCS concept): the second one uses streaming replication to verify it, and the third checks that the instance manager is working and that Postgres is up - not streaming. My proposed goal is to come up with an initial patch once 1.26.0 is out and start receiving feedback at an early stage. Thank you, |
|
The Proof of Concept developed by @leonardoce around the reliance on Kubernetes' liveness probe succeeded. The liveness probe endpoint provided by the instance manager returns a failure when isolation is detected. As a result, the operator requires no additional complexity, given that we reuse the Kubernetes probes infrastructure and let the kubelet do its job of triggering the instance's self-fencing. This is a very elegant and clean way to achieve the result, and most importantly, a Kubernetes native one. If you want to test the PoC on your station, and provide feedback, please see my comments here: #7466 (comment) |
|
Over this past weekend, I spent quite a bit of time going though patroni's design. I came to a different conclusion about how patroni works than what @bonesmoses posted upthread:
After spending some time in the Patroni code & docs last weekend, I came to the conclusion that patroni absolutely does rely on sync replication as the sole mechanism for fencing and durability. Any other mechanism that does self-healing by promoting a replica could allow for data loss - if it can promote a replica which does not have all writes. I think that Patroni's DCS failsafe is for resolving a situation where the consensus layer itself can become confused. Patroni DCS failsafe makes sure Patroni can't RECONFIGURE postgres and have both writers change their This is going to be true with every postgres clustering solution. Sync replication in postgres itself is the only thing protecting against losing data by promoting a replica without the latest writes. The cluster management layer must be able to understand which replica nodes are safe candidates for a promotion to writer without data loss.
First, it's very important to note that if CNPG is deployed in a cloud region with three AZs and three CNPG instances with AZ-anti-affinity and one sync replica, then CNPG will correctly protect data during an AZ network partition like the March 18 2025 incident in Azure East US where we lost network connectivity between one AZ and the other two AZs. If the writer was in the isolated AZ then it will stop accepting writes (because it can't sync to a second instance), and upon rejoining the CNPG cluster it will be immediately demoted. The k8s control plane and CNPG operator will always stay in the partition with two AZs. The only real protection against data loss during auto promotion (self-healing) in a network partition is sync replication. If a network partition separates any sync replica from the primary, then the primary must block writes until the cluster can safely be reconfigured. This POC design (#7465 #7466) is a good idea, because if there is a network partition then this code can demote an already-broken writer which might help trigger clients to reconnect. But this is not a "fencing" solution in the sense of protecting against lost writes; it's the sync replication that protects against lost writes by blocking writes entirely. The real underlying requirement is that CNPG needs to promote a new writer only when it's guaranteed that the replica has all writes. However the CNPG logic around promoting new writers has gaps that could allow users to configure in ways that allow data loss in less common situations, especially in topologies that are more complex than public cloud regions with three AZs. The CNPG logic around promoting new writers needs to be improved; this self-fencing design does not address the core problems. |
|
Hi @NikolayS As I mentioned before, this is not close, even if you go to the issue you will see that it's not "close" is marked as it because it was turn into a discussion and that it's clearly marked when you open the issue, with that being clear. Can you please add your comments into a proper way into this discussion? We really appreciate your commitment to improve CloudNativePG and find issues on it, but sadly, not everyone can follow a link from here or will follow a link after that link and probably will not even have a Linkedin account. We would love that you follow the process of posting all the information here in the right format so everyone can follow the discussion here, in the official place to discuss all the issues related to this, not minor discussion, and all the tickets that will follow this discussion. The discussion can always be linked to different issues, keeping a track from everything that will and could come out from this, like documentation, blog posts, bug fixes and even features. Again, we thank you for your contributions and deep research on this important matter and we also thank you for your deep compromise and collaboration on this. Regards, |
|
I think I invested enough effort to explain what's wrong. I see my asks in #7462 (reply in thread) are not heard. Our positions are radically different:
That being said, I won't be investing more of my resources in additional testing in nearest future, I think the issue with recent approach is explained well enough, for my bug report to be reopened and properly addressed. For fun, here is a picture for you and what Claude Opus 4.1 thinks about this – https://claude.ai/share/4c3c786b-5567-4639-8522-535cb9e2cf86, feel free to get it from there :) and one more (for #7572): |
|
I am closing this discussion, given that we have introduced the primary isolation check in 1.27 (enabled by default) and the failover quorum feature in 1.28 (see this webinar or our KubeCon NA 2025 talk for more information). |


Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Is there an existing issue already for this bug?
I have read the troubleshooting guide
I am running a supported version of CloudNativePG
Contact Details
[email protected]
Version
1.25 (latest patch)
What version of Kubernetes are you using?
1.32
What is your Kubernetes environment?
Self-managed: kind (evaluation)
How did you install the operator?
YAML manifest
What happened?
Split brain
If the primary has lost network, then it remains the primary, allowing writes, and a replica is promoted – a typical split brain
How to reproduce:
Set up in dind, details:
Steps:
kind create cluster --config kind-config.yamlkubectl apply --server-side -f https://raw.githubusercontent.com/cloudnative-pg/cloudnative-pg/release-1.25/releases/cnpg-1.25.1.yamlkubectl apply -f cnpg_test_cluster.yamldocker network disconnect kind kind-worker-xxxThis is a typical split brain. Any workload that origins from the same VM (e.g., pod is on the same node as the old primary) can generate writes to the old primary.
Of course, in some cases, it is ok to live with this – e.g., forbidding app pods to be on the same node setting up anti-affinity, but it is not possible in all the cases.
And it becomes even worse if we use, say, pg_cron, and have some periodic jobs generating some writes – this workload happens inside Postgres, and split brain becomes inevitable.
A personal note: I came from the Patroni world and see these problems as a show-stopper. We (Postgres.AI) have several customers of various sizes that seriously consider to use CNPG. I'm very curious what the maintainers think about these findings and if it can be solved somehow in the future. Thanks.
Cluster resource
Relevant log output
Code of Conduct
All reactions