Skip to content

[Bug]: Potential race condition in primary update switchover #11114

Closed as not planned

Description

@chunngaiau

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

No response

Version

1.29 (latest patch)

What version of Kubernetes are you using?

1.35

What is your Kubernetes environment?

Cloud: Google GKE

How did you install the operator?

YAML manifest

What happened?

A synchronous replica was not promoted as the new primary during an unsupervised primary update switchover. Instead a less up-to-date replica was promoted. There were WAL records in the synchronous replica that were never replicated to the new primary. This is because the new primary is chosen before the current primary is shutdown.

Timeline

  1. We have a 3-instance cluster. -2 was the primary and -1 and -3 were the replicas. Our relevant settings are:
spec:
  primaryUpdateStrategy: unsupervised
  primaryUpdateMethod: switchover
  postgresql:
    synchronous:
      dataDurability: required
      failoverQuorum: true
      method: any
      number: 1
  1. We added an entry to the spec.postgresql.shared_preload_libraries config which requires a restart.
  2. The operator correctly restarted -1 and -3 for the config change.
  3. The operator then selected -1 as the new replica before restarting -2. In this reconciliation iteration, all instances reported the same LSN.
  4. Fast shutdown was requested on -2. Since 4, it had written new WAL records. These new WAL records were replicated to -3 but not -1.
  5. After -2 was shutdown, -1 was promoted to the new primary.
  6. -3 fails to resume streaming from -1 because it is ahead of the fork point of -1's new timeline and crash-loops. -2 ran pg_rewind and successfully resumed streaming from the new replica. The logs we saw on -3 after the switchover are:
could not start WAL streaming: ERROR:  requested starting point 0/D000000 on timeline 2 is not in this server's history
DETAIL:  This server's history forked from timeline 2 at 0/C000130.
new timeline 3 forked off current database system timeline 2 before current recovery point 0/D0000A0
waiting for WAL to become available at 0/D0000B8

Our workaround for this is to now use primaryUpdateMethod: restart.

Expectations

In a cluster with synchronous replication enabled, we would not expect to see this error because the synchronous standby should be the replica selected to become the new primary. This error indicates that there were WAL records with potentially important data in them that were never replicated to the new primary.

The new primary should be selected after writes to the cluster have been stopped. Currently, the order is reversed, see below.

Code analysis

In the updatePrimaryPod method in cluster_upgrade.go, we select the second pod in the list which should be the replica with the highest LSN and updates the cluster's targetPrimary to this instance.

After that, this triggers a fast shutdown of the existing primary in the updateOldPrimary method in instance_controller.go.

It is possible that transactions could've been committed between when the new primary was selected and before shutdown is triggered on the existing primary. When using quorum-based synchronous replication (i.e. method: any), these transactions could've been replayed on any replica which can exclude the chosen new primary.

Cluster resource

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  annotations:
    kustomize.toolkit.fluxcd.io/prune: disabled
    prometheus.io/path: /metrics
    prometheus.io/port: "9187"
    prometheus.io/scrape: "true"
  labels:
    app: databroker-pg
  name: databroker-pg
  namespace: data
spec:
  affinity:
    enablePodAntiAffinity: true
    podAntiAffinityType: required
    topologyKey: topology.kubernetes.io/zone
  bootstrap:
    initdb:
      database: postgres
      owner: root
      secret:
        name: databroker-pg-root-user
  enablePDB: false
  imageCatalogRef:
    apiGroup: postgresql.cnpg.io
    kind: ImageCatalog
    major: 18
    name: databroker-pg-catalog
  instances: 3
  managed:
    roles:
    - bypassrls: true
      createdb: true
      createrole: true
      ensure: present
      login: true
      name: root
      passwordSecret:
        name: databroker-pg-root-user
      replication: true
      superuser: true
    services:
      disabledDefaultServices:
      - r
      - ro
  postgresql:
    parameters:
      checkpoint_timeout: "1800"
      cron.database_name: postgres
      cron.log_run: "off"
      cron.log_statement: "off"
      cron.max_running_jobs: "5"
      max_connections: "300"
      max_logical_replication_workers: "8"
      max_sync_workers_per_subscription: "4"
      max_worker_processes: "8"
      shared_buffers: 320MB
      wal_level: logical
      work_mem: 20MB
    shared_preload_libraries:
    - pg_cron
    synchronous:
      dataDurability: required
      failoverQuorum: true
      method: any
      number: 1
  primaryUpdateMethod: switchover
  resources:
    limits:
      cpu: 4
      memory: 1.75Gi
    requests:
      cpu: 500m
      memory: 1.75Gi
  storage:
    size: 20Gi
    storageClass: cloudnative-pg-gcp-ssd
  walStorage:
    size: 2Gi
    storageClass: cloudnative-pg-gcp-ssd

Relevant log output

| Timestamp    | Pod   | Log line (message or record.message)                                                                                                                                                                                                       | Parameters                                              |
|--------------|-------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------|
| 13:19:24.795 | cnpg  | The primary needs to be restarted, we'll trigger a switchover to do that                                                                                                                                                                   | { "currentprimary": "pod-2", "targetprimary": "pod-1" } |
| 13:19:24.795 | cnpg  | pod status (1 of 3)                                                                                                                                                                                                                        | { "name": "pod-2", "currentlsn": "0/C000060" }          |
| 13:19:24.795 | cnpg  | pod status (2 of 3)                                                                                                                                                                                                                        | { "name": "pod-1", "replaylsn": "0/C000060" }           |
| 13:19:24.795 | cnpg  | pod status (3 of 3)                                                                                                                                                                                                                        | { "name": "pod-3", "replaylsn": "0/C000060" }           |
| 13:19:25.020 | pod-1 | Setting myself as primary                                                                                                                                                                                                                  |                                                         |
| 13:19:25.020 | pod-1 | I'm the target primary, wait for the wal_receiver to be terminated                                                                                                                                                                         |                                                         |
| 13:19:25.026 | pod-1 | WAL receiver is still active, waiting                                                                                                                                                                                                      |                                                         |
| 13:19:25.041 | cnpg  | Setting primary label to unhealthy in the old primary during failover                                                                                                                                                                      | { "pod": "pod-2" }                                      |
| 13:19:25.157 | pod-2 | This is the former primary instance. Shutting it down to allow it to be demoted to a replica.                                                                                                                                              |                                                         |
| 13:19:25.199 | pod-2 | received fast shutdown request                                                                                                                                                                                                             |                                                         |
| 13:19:25.201 | pod-2 | aborting any active transactions                                                                                                                                                                                                           |                                                         |
| 13:19:25.439 | pod-3 | replication terminated by primary server                                                                                                                                                                                                   |                                                         |
| 13:19:30.198 | pod-1 | terminating walreceiver due to timeout                                                                                                                                                                                                     |                                                         |
| 13:19:30.198 | pod-2 | terminating walsender process due to replication timeout                                                                                                                                                                                   |                                                         |
| 13:19:30.219 | pod-2 | database system is shutdown                                                                                                                                                                                                                |                                                         |
| 13:19:31.071 | pod-1 | received promote request                                                                                                                                                                                                                   |                                                         |
| 13:19:31.071 | pod-1 | terminating walreceiver process due to administrator command                                                                                                                                                                               |                                                         |
| 13:19:31.209 | pod-1 | waiting for WAL to become available at 0/C000148                                                                                                                                                                                           |                                                         |
| 13:19:31.348 | pod-1 | redo done at 0/C0000B8 system usage: CPU: user: 0.00 s, system: 0.00 s, elapsed: 13.45 s                                                                                                                                                   |                                                         |
| 13:19:31.629 | pod-1 | selected new timeline ID: 3                                                                                                                                                                                                                |                                                         |
| 13:19:33.149 | pod-1 | liveness check failed: instance connectivity error for instance pod-2 with ip 10.243.4.122 (requestTimeout:1000 connectionTimeout:1000): Get "https://10.243.4.122:8000/failsafe": dial tcp 10.243.4.122:8000: connect: connection refused |                                                         |
| 13:19:35.193 | pod-2 | This is an old primary instance, waiting for the switchover to finish                                                                                                                                                                      |                                                         |
| 13:19:35.193 | pod-2 | Switchover completed                                                                                                                                                                                                                       |                                                         |
| 13:19:35.194 | pod-2 | Waiting for the new primary to be available                                                                                                                                                                                                |                                                         |
| 13:19:36.295 | cnpg  | Setting primary label                                                                                                                                                                                                                      | { "pod": "pod-1" }                                      |
| 13:19:36.295 | cnpg  | Setting replica label                                                                                                                                                                                                                      | { "pod": "pod-2" }                                      |
| 13:19:37.256 | pod-2 | Starting up pg_rewind                                                                                                                                                                                                                      |                                                         |
| 13:19:37.396 | pod-2 | pg_rewind: servers diverged at WAL location 0/C000130 on timeline 2                                                                                                                                                                        |                                                         |
| 13:19:37.397 | pod-2 | pg_rewind: rewinding from last common checkpoint at 0/C0000B8 on timeline 2                                                                                                                                                                |                                                         |
| 13:19:37.424 | pod-1 | requested starting point 0/D000000 on timeline 2 is not in this server's history                                                                                                                                                           |                                                         |
| 13:19:37.425 | pod-3 | could not start WAL streaming: ERROR:  requested starting point 0/D000000 on timeline 2 is not in this server's history. DETAIL:  This server's history forked from timeline 2 at 0/C000130.                                               |                                                         |
| 13:19:37.387 | pod-3 | new timeline 3 forked off current database system timeline 2 before current recovery point 0/D0000A0.                                                                                                                                      |                                                         |
| 13:19:42.135 | pod-2 | pg_rewind: Done!                                                                                                                                                                                                                           |                                                         |
| 13:19:42.136 | pod-2 | Demoting instance                                                                                                                                                                                                                          |                                                         |
| 13:19:42.727 | pod-2 | the database is starting up                                                                                                                                                                                                                |                                                         |
| 13:19:43.066 | pod-2 | redo starts at 0/C000060                                                                                                                                                                                                                   |                                                         |
| 13:19:43.068 | pod-2 | consistent recovery state reached at 0/C0050B0                                                                                                                                                                                             |                                                         |
| 13:19:43.068 | pod-2 | database system is ready to accept read-only connections                                                                                                                                                                                   |                                                         |

# pod-3 then repeats its errors:

could not start WAL streaming: ERROR:  requested starting point 0/D000000 on timeline 2 is not in this server's history. DETAIL:  This server's history forked from timeline 2 at 0/C000130.
new timeline 3 forked off current database system timeline 2 before current recovery point 0/D0000A0.

Code of Conduct

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

Activity

  1. added
    bug 🐛
    triage
    on Jul 2, 2026
  2. dosubot commented on Jul 2, 2026

    @dosubot

    Hi @chunngaiau! I'm Dosu and I'm helping the CloudNativePG team.

    Your analysis of the race condition is correct. The fundamental issue is that the target primary is selected before the current primary is shut down in updatePrimaryPod [1]. Between target selection and the fast shutdown signal, the old primary can still accept writes and replicate them to a different synchronous replica than the chosen target — exactly what you observed.

    The code flow is:

    1. switchPrimary() calls setPrimaryInstance() to designate the new target [2]
    2. Only afterwards does the failover reconciliation mark the old primary unhealthy and signal shutdown [3]

    With method: any, number: 1, PostgreSQL can acknowledge commits to either replica. So WAL committed after target selection but before shutdown can land on the non-chosen replica (pod-3 in your case), causing the timeline divergence you saw.

    Related issues: Issue #11110 tracks a related problem where received LSN (not replay LSN) is used for target selection, and issue #10103 covers label-transition timing gaps during switchover with synchronous replication [4] [5].

    Mitigations available today: Your cluster already has failoverQuorum: true set, which is supposed to validate that the promoted replica has committed data [6]. However, the quorum check validates availability of synchronous replicas for failover — it doesn't fully address the window where new WAL is written after the LSN snapshot is taken for target selection.

    Recent improvements: A Primary Lease mechanism was merged in June 2026 that adds mutex-like synchronization at promotion time [7], and timeline validation fixes prevent replicas from consuming stale WAL [8]. Upgrading to a version containing these changes would add defense-in-depth layers.

    Workaround consideration: Using method: first instead of method: any would make the synchronous standby deterministic (always the same replica), making it far more likely that the target selected by LSN sorting is the sync standby. Your current workaround of primaryUpdateMethod: restart also avoids the issue entirely by not doing a switchover.

    To reply, just mention @dosu.


    Docs are dead. Just use Dosu.

    Leave Feedback Ask Dosu about cloudnative-pg Share Dosu with your team

  3. ardentperf commented on Jul 2, 2026

    @ardentperf
    Contributor

    1.30 adds the new primary lease which i think helps a lot here by making sure an old primary shuts down before the new primary is promoted

    i'm thinking we just need to look at the logic in 1.30 - is there a way we can have the operator use this same lease to select a new primary? then it would ensure old primary shuts down first (or is confirmed fenced/dead), before it gathers LSNs to determine a new primary. but im not sure if this is easy... right now i dont think theres a way to say currentPrimary is "unassigned/none/owned-by-operator"? i do think this is one of the last remaining gaps in the cluster management logic

    @leonardoce curious what you think

    (other gap might be around adding and removing replicas, i'm not sure if we added the code yet to block failovers during the time when they transition from not-considered-for-failoverquorum to considered-for-failover-quorum)

  4. github-actions commented on Oct 14, 2026

    @github-actions
    Contributor

    This issue is stale because it has been open for 60 days with no activity.

  5. github-actions commented on Oct 29, 2026

    @github-actions
    Contributor

    This issue was closed because it has been inactive for 14 days since being marked as stale.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Stalebug 🐛triage

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions