Skip to content

[Bug]: Split-brain in case of network partition #7407

Closed

Description

@NikolayS

Is there an existing issue already for this bug?

  • I have searched for an existing issue, and could not find anything. I believe this is a new bug.

I have read the troubleshooting guide

  • I have read the troubleshooting guide and I think this is a new bug.

I am running a supported version of CloudNativePG

  • I have read the troubleshooting guide and I think this is a new bug.

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:

  • kubectl version: v1.32.3
  • Kustomize Version: v5.5.0
  • Server Version: v1.32.2
  • kind version 0.27.0
  • kind-config.yaml – below
kind: Cluster
apiVersion: [kind.x-k8s.io/v1alpha4](http://kind.x-k8s.io/v1alpha4)
nodes:
  - role: control-plane
  - role: worker
  - role: worker
  - role: worker
cat cnpg_test_cluster.yaml
apiVersion: [postgresql.cnpg.io/v1](http://postgresql.cnpg.io/v1)
kind: Cluster
metadata:
  name: cnpg-test-cluster
spec:
  instances: 3
  storage:
    size: 1Gi

Steps:

  1. Create the cluster: kind create cluster --config kind-config.yaml
  2. Install CNPG operator: kubectl apply --server-side -f https://raw.githubusercontent.com/cloudnative-pg/cloudnative-pg/release-1.25/releases/cnpg-1.25.1.yaml
  3. Deploy kubectl apply -f cnpg_test_cluster.yaml
  4. Identify the primary node and disconnect it from the network using docker network disconnect kind kind-worker-xxx
  5. Observe that CNPG promoted a new primary node.
  6. Bash into the old primary node using docker exec, and bash into the postgres pod inside the node. Postgres on this node is still primary.
  7. And iptables rules are stale because no updates from k8s API server, of course ==> any workload originated locally (e.g. a pod running on the same node) still talks to the old primary. Split brain.

This 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.

  1. The term "fencing" used in the docs looks like "manual fencing" rather than what one could expect from a system with auto-failover. And it won't be possible to use if, again, the primary lost network – imagine it happened, how will fencing works? The note is not achieavable.

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

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

Activity

  1. added
    triage
    on Apr 22, 2025
  2. dosubot commented on Apr 22, 2025

    @dosubot

    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 pg_rewind to realign the former primary node when it reconnects to the network, restarting it as a standby to prevent split-brain scenarios. The operator automatically sets the most aligned replica as the new primary in case of a detected failure on the primary [2][3].

    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

  3. added
    bug 🐛
    on Apr 22, 2025
  4. NikolayS commented on Apr 22, 2025

    @NikolayS
    Author

    AI is great, but answers provided by the bot are not fully relevant, my questions remain.

  5. bonesmoses commented on Apr 22, 2025

    @bonesmoses

    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.

  6. changed the title [-][Bug]: Split brain in case of network partition[/-] [+][Bug]: Split-brain in case of network partition[/+] on Apr 23, 2025
  7. NikolayS commented on Apr 23, 2025

    @NikolayS
    Author

    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.

  8. ardentperf commented on Apr 28, 2025

    @ardentperf
    Contributor

    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 dataDurability set to required and not to preferred) should further reduce risk here. if a postgres writer on a k8s node loses network connectivity then it will stop accepting writes, since it cannot get quorum on the writes. yes - theoretically you could have a writer and one reader lose connectivity to the k8s control plane - but k8s will still stop any further incoming traffic to the node in general.

    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?

  9. gbartolini commented on Apr 29, 2025

    @gbartolini
    Contributor

    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:

    1. Continuous backup
    2. Synchronous replication
    3. Shared-nothing architectures through:

    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.

  10. added
    enhancement 🪄
    and removed
    bug 🐛
    on Apr 29, 2025
  11. added this to the Next milestone on Apr 29, 2025
  12. 2 remaining items

  13. bonesmoses commented on Apr 29, 2025

    @bonesmoses

    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.

  14. leonardoce commented on Apr 29, 2025

    @leonardoce
    Contributor

    Hi Shaun.

    A node without the leadership key is automatically unroutable due to the REST interface

    That's true, but unfortunately, kube-proxy won't change the iptables rules when the node can't reach the API server.
    This affects every workload, CNPG, and Patroni inside Kubernetes, too.
    Because of that, the last known iptables rules will be kept, and the old partitioned primary will still be reachable.

    and Patroni goes a step further and stops the Postgres service until it can re-establish consensus for the rewind.

    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

  15. gbartolini commented on Apr 29, 2025

    @gbartolini
    Contributor

    Hi Shaun,

    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.

    Could you please help me better understand this by providing more details?

    Thanks,
    Gabriele

  16. bonesmoses commented on Apr 29, 2025

    @bonesmoses

    Could you please help me better understand this by providing more details?

    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 synchronous_standby_names to ANY 1 (node2, node3), then the Primary can't write if it loses contact with both of the downstream nodes. You're also enforcing minimum transaction latency equal to the closest of those nodes in your architecture. You're using Postgres to make up for some deficiency in the design of the HA mechanism itself.

    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.

  17. NikolayS commented on Apr 29, 2025

    @NikolayS
    Author

    @gbartolini thank you for response.

    Why don't you use Patroni or follow the same path?

    @bonesmoses

    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

    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

  18. NikolayS commented on Apr 29, 2025

    @NikolayS
    Author

    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.

    What happened to this consideration?

  19. gbartolini commented on Apr 30, 2025

    @gbartolini
    Contributor

    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):

    1. The API server cannot be reached.
    2. At least one replica’s WAL receiver is not connected to the primary.
    3. At least one instance is unreachable via the instance manager's REST API (we have information in the last Status of the Cluster resource successfully retrieved by the instance manager from the API server).

    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,
    Gabriele

  20. locked and limited conversation to collaborators on Apr 30, 2025
  21. converted this issue into a discussion #7462 on Apr 30, 2025
  22. modified the milestones: Next, 1.26.0 on May 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement 🪄help wanted 🆘no-stale

Projects

  • Status
    Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions