Repository navigation
Closed
Copy link
Description
Version
trunk (main)
What happened?
i'm reviewing the code in reconcileTargetPrimaryForNonReplicaCluster() and it might be missing some logic?
i'm thinking automatic promotion as part of self-healing is only safe (ie. no data loss) in conjunction with sync replication. i'm not sure we should fully trust any methodologies based on trying to flush WAL.
Edit (4-May-2025): can skip this initial design proposal below the line here, and just go straight to the design proposal in the first comments.
- Quorum-Based: assuming that standbyNamesPre/Post and maxStandbyNamesFromCluster are unset, only consider promoting the first N entries in instancesStatus[], where N is
synchronous.number - unreachable_replicas.- (if synchronous.number == 0 then we should not auto promote anyone. possibly we should default synchronous.number to
1on all cnpg clusters with at least one replica? and shoulddataDurabilitydefault topreferredwith 1 replica andrequiredwith 2+ replicas?) - still need to work out the formula when standbyNamesPre/Post or maxStandbyNamesFromCluster are present
- still need to think through
preferreddurability a bit more - with
synchronous.number=1even a single unreachable replica would mean no promotion, but i think this is likely the behavior we want? would it make sense to have the default to up to2if there are 3+ replicas? i think we always want at least one async replica available for pod disruption budgets during maintenance.
- (if synchronous.number == 0 then we should not auto promote anyone. possibly we should default synchronous.number to
- Priority-Based: only consider promoting entries in instancesStatus[] that are known sync replicas?
- might be a race condition where an unavailable higher-priority replica has just come back online, and postgres has just demoted the final
syncreplica back topotential, but cnpg is not yet aware of this fact. if cnpg promotes the replica that it thought wassyncthen there could be data loss.
- might be a race condition where an unavailable higher-priority replica has just come back online, and postgres has just demoted the final
this is fairly complex to reason through, so would be good to discuss further
Code of Conduct
- I agree to follow this project's Code of Conduct
Reacted by dosubot
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
- StatusShow more project fieldsDone
Activity
dosubot commentedon May 3, 2025
The
reconcileTargetPrimaryForNonReplicaCluster()function currently does not explicitly verify quorum during automatic promotion. It selects the most advanced instance for promotion based on the sorted list of instances, without considering the quorum or synchronous replication settings [1].Your suggestion to incorporate quorum-based and priority-based logic for automatic promotion is valid, especially in scenarios where data consistency and safety are critical. Implementing a check for
synchronous.numberand adjusting the promotion logic based on the number of reachable replicas could enhance the reliability of the self-healing process. Additionally, ensuring that only known synchronous replicas are considered for promotion aligns with best practices for maintaining data integrity.This approach would require modifications to the current logic to account for synchronous replication settings and potentially defaulting
synchronous.numberto1in clusters with replicas, as you suggested. This would prevent automatic promotion when no synchronous replicas are available, reducing the risk of data loss.Discussing this further with the team and considering these changes could improve the robustness of the automatic promotion mechanism in CloudNativePG.
To reply, just mention @dosu.
Docs are dead. Just use Dosu.
ardentperf commentedon May 4, 2025
interesting background reading:
ardentperf commentedon May 4, 2025
FYI
some interesting patroni code/logic for automated failover with quorum based sync replication is at https://github.com/patroni/patroni/blob/8f22fd255efc5710e4fd1853f12c34abf893abe6/patroni/quorum.py#L55-L64
took me a bit longer to go through the patroni logic for priority repl. from my read of the code right now, i don't think they ever allow a value for
synchronous.numberwhich is less than the count of entries insynchronous_standby_namesand i think this is how they avoid the race condition i was concerned about above, but it also results in the following caveat mentioned in the patroni docs:https://patroni.readthedocs.io/en/latest/replication_modes.html#synchronous-mode
in fact i think the number is always equal to the count except for when there are no entries and patroni->synchronous_mode_strict is enabled, in which case
synchronous.numberis set to1to intentionally block writes until a replica becomes available.key files are patroni/ha.py and patroni/postgresql/sync.py
by default, i think patroni uses a single sync replica (
synchronous_node_count=1) and the HA cycle which runs everyloop_waitseconds (default 10) can potentially updatesynchronous_standby_namesto a different node on each cycle, though there's logic to reduce churn on this (cf https://patroni.readthedocs.io/en/latest/replication_modes.html#maximum-lag-on-synchronous-node )ardentperf commentedon May 4, 2025
i have an idea for cnpg which i think might solve for both quorum and priority replication, with both required and preferred durability. i think this naturally fits into cnpg's code/design and supports its flexibility, while providing a correct & strong guarantee that cnpg will never lose data by promoting an out-of-date replica - even with esoteric combinations of multiple failures on complex distributed topologies.
synchronous_standby_namesreconcileTargetPrimaryForNonReplicaCluster()to perform a simple quorum check and to only promote a new primary (use existing code; no changes) if the quorum check succeedsQuorum Check Algorithm
the algorithm below is along similar lines to distributed systems theory around quorum based consistency, often expressed something like
R + W > N == strong consistency. in our case:synchronous_standby_namessynchronous.numberor zero. the zero value effectively blocks promotions during intermediate states with changes tosynchronous_standby_names(before the number value takes effect and before postgres begins blocking writes with insufficient levels of sync replication)synchronous_standby_nameswhere we can know the latest applied LSN, to guarantee at least one has the latest writescluster configuration state changes need to be handled correctly, this is a tricky part. i've taken a swing at handling them correctly in the design below. Alexander's algorithm in
patroni/quorum.pyis also worth continued study to see if the thinking seems to line up, particularly around postgres internals and catalogs.to guarantee safety during state changes or with stale information: N can be too large, but it can never be too small. R and W can be too small, but they can never be too large.
Design Specifics
synchronous_standby_names. the value ofsynchronous_standby_namesalready reflects the effects ofdataDurability=preferredandmaxStandbyNamesFromCluster(if either is in effect).synchronous_standby_names- if we can't reach the writer then we'll use the stored value. it is ok if a saved N value is too large but it can't be too small. i think i have these rules right:pg_stat_replication. if a primary crashes, we can get a NUM_SYNCWRITERS value that's too small, but we can't get one that's too large.standbyNamesPre/standbyNamesPost), increase a counter NUM_HEALTHY if the replica instance has aPostgresqlStatusListentry in thestatusvariable indicating it's reachable and promotable.sync_stateofquorumandsync- but also includespotentialbecause postgres can change betweenpotentialandsyncby itself. (though i'm not sure we actually need to explicitly check these values in the algorithm; we can generally just look for all values insynchronous_standby_names.)pg_stat_replicationon the writer and finds its corresponding entry. ifstate=streamingthen increase a counter NUM_SYNCWRITERS. once we reach the value ofsynchronous.number, stop checking (don't allow a larger value).synchronous.numberor the value zero. use thepg_stat_replication.statecheck to decide when it's safe to move from zero back up to the value ofsynchronous.number.pg_stat_replication.state? probably we only need to check this after changes tosynchronous_standby_namesor after promoting a new writer. postgres should block writes if they aren't on enough replicas". i think the key question (and patroni had to solve this too) is "how do you know the moment when the newsynchronous_standby_namesis applied. i think patroni looks atpg_stat_replication.statefor this; that seems like reasonable logic to me. continuing to check pg_stat_replication should not be needed oncesynchronous_standby_namesis confirmed applied. possibly we only zero it out when first changing cluster config, and stop checking once we're 100% sync repl config is applied.synchronous_standby_names)FAQ
Don't you need some kind of consensus, voting, or election algorithm to safely choose writers?
CNPG (already) relies on kubernetes primitives to guarantee that two reconciliation loops cannot run concurrently. Kubernetes itself needs these same guarantees to ensure that only one instance of controller-manager and scheduler are actively running, so these primitives need to be correct for the safety of kubernetes itself. This is a well-trod problem space in the kubernetes community and CloudNativePG's philosophy is to directly integrate kubernetes native consensus and leader election.
A few good sources of more information are https://kubernetes.io/docs/concepts/architecture/leases/ and https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/
More specifically, the CNPG operator relies on controller-runtime which explicitly implements a leader election algorithm based on kubernetes leases. cf https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/manager#Options
What about stale values being used in quorum checks during rolling maintenance or multiple compounding failures?
This design guarantees safety while avoiding the need for voting, election, or two-phase promotions with the rules about reducing NUM_SYNCWRITERS before any cluster config operations and careful ordering of changes to
synchronous_standby_names.The key rule is that N can always be too big and R/W can always be too small.
This simple reasoning guarantees safety during any state change, as long as the code follows the rule.
What are a few more things we need to think carefully about?
synchronous_standby_nameson a writer, at what exact moment does each individual postgres backend/connection start blocking commits if they aren't confirmed in NN remote places?synchronous_standby_names? Is any special action needed to make sure NUM_HEALTHY remains an accurate representation of candidates for latest commits/LSNs?kubectl cnpg promoteimplementation provide a provable guarantee of safety?Does this provide the same compromise/caveat as patroni's priority algorithm, where failures might cause writes to hang until the next reconciliation loop?
This algorithm guarantees safety & durability while supporting a lot of flexibility in allowed configurations.
When configured the same as patroni, the same caveats generally apply. For example, the following configuration might result in postgres suspending writes after sync replica failure until the next operator reconciliation loop:
synchronous.number=1and a single replica (instances=2)maxStandbyNamesFromCluster=synchronous.numberPatroni's recently added quorum algorithm has an ability to avoid the "suspended writes" caveat. Similarly, CNPG with this design would never have writes hang for NN seconds waiting for a reconciliation loop if:
synchronous.numberis less than BOTH the replica count (instance count minus one) and alsomaxStandbyNamesFromClusterstandbyNamesPre/standbyNamesPostthat ensuresynchronous.numberis less than the total count of entries insynchronous_standby_namesset by CNPGGenerally speaking, writes hang if there aren't enough healthy replica instances, which is a behavior that's easy to understand and reason about.
How do you get similar behavior to patroni's
synchronous_mode_strict?I think the
placeholderInstanceNameSuffixlogic inexplicitSynchronousStandbyNamesDataDurabilityRequired()provides the same behavior withdataDurability=required, but this should be verified.Does this still guarantee safety/durability with complex topologies like sync replica/remote clusters and async local replicas?
Yes. A couple examples are worked out below.
Should we reject configurations where automatic replica promotion would never safely be possible as a self-healing mechanism, because it's impossible to ever determine a candidate for promotion that doesn't lose data?
This would include any configuration with multiple instances and without sync replication configured. It also includes some configurations with remote replica clusters in
standbyNamesPre/standbyNamesPost. In traditional deployments where failovers are always managed manually by admins, these configurations are very common. Given CloudNativePG's tight coupling to kubernetes, I think it's reasonable to reject configurations which cannot support any automatic replica promotion. Whether there should be a way to override this might be an interesting discussion.Configurations with a single instance (writer) and no replicas at all should not be rejected.
What if safety/durability means there's no way to automatically promote a replica after a failure? Can an admin manually push a configuration that might cause data loss?
Even if we block provisioning of configurations that break automatic promotion, it's unavoidable that some failures will lead to this situation.
One obvious example is losing both the writer and a sync reader. There are times where CNPG cannot guarantee/prove that it has a replica with the latest commits. If this happens, there is no safe way to automatically promote.
If we ever get into a state where we can't safely promote a new writer, then we probably need to label it very clearly as a "possible data loss" state - and make sure any manual administrator-executed corrective actions are clearly labeled as "perform_this_action_with_possible_data_loss".
For example, an administrator may decide the data loss risk is acceptable and try to lower the value of
synchronous.numberor remove entries fromstandbyNamesPre/standbyNamesPost.example 1: complex topology with sync remote replica clusters
one writer with 6 replicas (instances=7) and
synchronous.number=3andmaxStandbyNamesFromCluster=3and 2 replica clusters instandbyNamesPreand priority replication (FIRST) anddataDurability=required.write0 [ pre1 pre2 sync3 sync4 sync5 ] nosync6 nosync7 nosync8 ...
synchronous_standby_names=FIRST 3 [ p1 p2 s3 s4 s5 ]NUM_HEALTHY is never more than 3, because [p1 p2] are always unknown.
if any of [s3 s4 s5] is unavailable when a writer fails, then the (NUM_HEALTHY + NUM_SYNCWRITERS > 5) check fails and we cannot safely promote. under a quorum model, the unavailable local instance [s5] could have been the only local instance with the latest commit - the quorum model can't guarantee otherwise. if [nosync8] becomes unavailable then it's fine to promote any local instance with the latest LSN - even if somehow [nosync6] had jumped ahead of [s3 s4 s5]. this shouldn't happen - but reconcileTargetPrimaryForNonReplicaCluster only needs its already-existing simple LSN sort, once the quorum check succeeds.
example 2: simple two-instance cluster with preferred durability
one writer with 1 replica (instances=2) and
synchronous.number=1anddataDurability=preferredhealthy: write0 [sync1] ...
synchronous_standby_names=[ s1 ]when the replica is healthy, it is included in NUM_HEALTHY. the (NUM_HEALTHY + NUM_SYNCWRITERS > 1) check passes and we can promote the replica if the writer fails.
unhealthy: write0 [] nosync1 ...
synchronous_standby_names=[ ]when the replica is unhealthy, the ( NUM_HEALTHY > 0 ) check fails and we cannot promote the replica if the writer fails.
example 3: standard three-instance cluster with a sync remote replica cluster, misconfigured
one writer with 2 replicas (instances=3) and
synchronous.number=1and one replica cluster in standbyNamesPost and quorum replication (ANY) anddataDurability=requiredwrite0 [ sync1 sync2 sync3 post4 ] ...
synchronous_standby_names=ANY 1 [ s1 s2 s3 p4 ]NUM_HEALTHY is never more than 3, because [p4] is always unknown. the (NUM_HEALTHY + NUM_SYNCWRITERS > 4) check always fails and this configuration can never safely promote any replicas.
this is correct behavior to avoid data loss, because the replica cluster might be the only instance with the latest writes - we can't guarantee otherwise.
example 4: standard three-instance cluster without maxStandbyNamesFromCluster, network partition
one writer with 2 replicas (instances=3) and
synchronous.number=1anddataDurability=requiredwrite0 [ sync1 sync2 ] ...
synchronous_standby_names=ANY 1 [ s1 s2 ]orFIRST 1 [ s1 s2 ]network partition isolates writer from both replicas: writer will stop accepting writes and the operator cannot communicate with the writer. NUM_HEALTHY is 2 (replicas). as long as no cluster reconfigurations were in progress, stored value of NUM_SYNCWRITERS is 1. the (NUM_HEALTHY + NUM_SYNCWRITERS > 2) check passes and we safely promote the replica with the most advanced LSN.
network partition isolates one replica from [writer and other replica and CNPG operator]: writer will continue accepting writes and the operator cannot communicate with the single partitioned replica. NUM_HEALTHY is 1 (replica). NUM_SYNCWRITERS is 1. if a writer failure occurs during the partition, then the (NUM_HEALTHY + NUM_SYNCWRITERS > 2) check fails and we cannot safely promote the replica.
network partition isolates [writer and one replica] from [CNPG operator and other replica]: (nb. this is not possible in a public cloud region with three AZs and three instances and correctly configured anti-affinity.) writer will continue accepting writes. the operator cannot communicate with the writer. the operator evaluates NUM_HEALTHY to be 1 (replica). as long as no cluster reconfigurations were in progress, stored value of NUM_SYNCWRITERS is 1. the (NUM_HEALTHY + NUM_SYNCWRITERS > 2) check fails and we cannot safely promote any replicas. this prevents the operator from promoting a replica which might have been missing writes.
summary: a network partition never causes the writer to pause writes while waiting for a reconciliation loop. however we can't tolerate writer failure during a network partition even with a sync replica that's available & healthy & promotable. it might be possible to fix this with further future enhancements.
example 5: standard three-instance cluster with maxStandbyNamesFromCluster set, network partition
one writer with 2 replicas (instances=3) and
synchronous.number=1anddataDurability=requiredandmaxStandbyNamesFromCluster=1write0 [ sync1 ] nonsync2 ...
synchronous_standby_names=[ s1 ]network partition isolates writer from both replicas: writer will stop accepting writes and the operator cannot communicate with the writer. NUM_HEALTHY is 1 (replica). as long as no cluster reconfigurations were in progress, stored value of NUM_SYNCWRITERS is 1. the (NUM_HEALTHY + NUM_SYNCWRITERS > 1) check passes and we safely promote the replica with the most advanced LSN.
network partition isolates sync replica from [writer and nonsync replica and CNPG operator]: writer will stop accepting writes. the operator cannot communicate with the partitioned sync replica. in the next reconciliation cycle, operator's already-existing code will detect sync1 is unhealthy and will reconfigure
synchronous_standby_names=[ s2 ](changing the second replica from nonsync to sync). after the reconfiguration, the writer will begin accepting writes again. if a writer failure occurs before this reconfig, then the (NUM_HEALTHY + NUM_SYNCWRITERS > 1) check fails. if a writer failure occurs after this reconfig, then the (NUM_HEALTHY + NUM_SYNCWRITERS > 1) check succeeds and we can promote.network partition isolates nonsync replica from [writer and sync replica and CNPG operator]: writer will continue accepting writes. the operator cannot communicate with the partitioned nonsync replica. if a writer failure occurs, then the (NUM_HEALTHY + NUM_SYNCWRITERS > 1) check succeeds and the sync replica can be promoted.
network partition isolates [writer and sync replica] from [CNPG operator and nonsync replica]: (nb. this is not possible in a public cloud region with three AZs and three instances and correctly configured anti-affinity.) writer will continue accepting writes. the operator cannot communicate with the writer. the operator evaluates NUM_HEALTHY to be 0 (replicas). as long as no cluster reconfigurations were in progress, stored value of NUM_SYNCWRITERS is 1. the (NUM_HEALTHY + NUM_SYNCWRITERS > 1) check fails and we cannot safely promote any replicas. this prevents the operator from promoting the replica which might have been missing writes.
network partition isolates [writer and nonsync replica] from [CNPG operator and sync replica]: (nb. this is not possible in a public cloud region with three AZs and three instances and correctly configured anti-affinity.) writer will stop accepting writes. the operator cannot communicate with the writer. the operator evaluates NUM_HEALTHY to be 1 (replica). as long as no cluster reconfigurations were in progress, stored value of NUM_SYNCWRITERS is 1. the (NUM_HEALTHY + NUM_SYNCWRITERS > 1) check succeeds and the sync replica can be promoted.
summary: a network partition sometimes causes writers to pause writes while waiting for a reconciliation loop, but we can handle writer failure during a network partition if a sync replica is available & healthy & promotable.
example 6: three-instance local cluster with quorum sync to two remote clusters in proximate (low latency) data centers, federated k8s
one writer with 2 replicas (instances=3) and two replica clusters in
standbyNamesPostand quorum replication (ANY) andsynchronous.number=3anddataDurability=requiredwrite0 [ sync1 sync2 post3 post4 ] ...
synchronous_standby_names=ANY 3 [ s1 s2 p3 p4 ]NUM_HEALTHY is never more than 2, because [p3 p4] are always unknown. if the writer fails, the (NUM_HEALTHY + NUM_SYNCWRITERS > 4) check passes and we can promote a new writer. if any of [s1 s2] fails, then writes are temporarily synchronous to both external clusters, and we can still promote a replica if there's a writer failure.
the two remote clusters might be able to be single-instance clusters with no replicas (as long as this doesn't disrupt maintenance operations) for a 3-1-1 topology. if a switchover is ever needed (demoting the primary cluster), instance counts and configurations can be adjusted at that time.
optionally, a third replica could be considered on the local cluster along with setting
maxStandbyNamesFromCluster=2for a 4-1-1 topology. in this casesynchronous_standby_nameswould be set identically to above - however if any of [s1 s2] fails, then CNPG operator will remove the unhealthy replica fromsynchronous_standby_namesin the next reconciliation loop and add nonsync5 tosynchronous_standby_names.summary: as illustrated in example 3, the value of
synchronous.numbermust be greater than the total number of entries instandbyNamesPreandstandbyNamesPost. otherwise we can never safely promote a new writer in the local cluster.ardentperf commentedon May 4, 2025
nb. using this (technically quorum-based) approach even for the priority config would have the advantage of avoiding the race problem i mentioned upthread around an instance becoming healthy before cnpg could detect it, and also the advantage that the whole durability model remains as a single unified approach that's easier to reason about
ardentperf commentedon May 5, 2025
think i figured out how to handle state changes
we just need to make sure not to overcalculate the WRITE factor. at any given time, the value we use for WRITE needs to be <= the actual number of synchronous replicas that the postgres database has.
i think we just reduce this whenever we do any kind of cluster operation that we know will trigger a change in physical replication, and we only increase it by pulling proof from
pg_stat_replicationthat replication is healthy and synchronous.i'm going to edit the design proposal above (again ) and change literal
synchronous.numberto be NUM_SYNCWRITERS which reflects a minimum known value (the real number of sync writers can be higher but not lower)ardentperf commentedon May 7, 2025
chatted through the algorithm with @leonardoce on slack yesterday. we're currently thinking that counting healthy streaming replicas is not part of W (i also edited the design comment above last night after this discussion). all that matters for W is the fact that postgres will block COMMIT for any transaction which is not confirmed on W replicas; as long as COMMIT will be blocked then we know we can't lose data. (W is zero during state changes.)
@leonardoce sketched out this updated basic algorithm on a white board today, based on our discussion yesterday. I believe this is correct:
gbartolini commentedon May 19, 2025
In my opinion, this is more of a feature request than a bug. Other opinions?
18 remaining items
gbartolini commentedon Jul 23, 2025
Given that we are still missing documentation and E2E tests, I suggest that we add this feature as experimental in 1.27 through an annotation (instead of an option in the CRD), and target 1.28 for the inclusion. This will allow us to get feedback from public, preferably in chaos engineering driven environments. Thoughts?
mnencia commentedon Jul 24, 2025
To clarify that this is an experimental feature, we decided to use an annotation instead of a field in the CRD to enable it.
gbartolini commentedon Jul 29, 2025
Bummer, we should have used the
alpha.cnpg.io/failoverQuorumannotation.feat: introduce experimental support for failover quorum (cloudnative…