Skip to content

[Bug]: cnpg restart proceeds to switchover with an unpromotable (replay-lagged) replica #11110

Open

Description

@aleksandar-had

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.28 (latest patch)

What version of Kubernetes are you using?

1.36

What is your Kubernetes environment?

Other

How did you install the operator?

YAML manifest

What happened?

During a controlled operator upgrade (1.28.0 to 1.28.2) we ran a rolling restart of a 3-instance cluster (kubectl cnpg restart, primaryUpdateMethod: switchover). The cluster sustains a very high write rate, around 250 GB/hour of WAL, and its replicas chronically lag on WAL replay (the apply side), often by several minutes even in steady state.

The restart rolled through the replicas first and then triggered a switchover on the primary. At that point both replicas were far behind on replay, roughly 15 and 20 minutes. The operator went ahead with the switchover anyway and demoted the primary while no replica was caught up enough to be promoted quickly.

Sequence:

  1. The primary got a fast shutdown and stopped accepting writes as soon as its shutdown checkpoint finished (under 30s). New connections were rejected with 57P03 ("the database system is shutting down").
  2. The rolling update selected the switchover target as the most advanced replica by received WAL position (podList.Items[1]). The only precondition it checked before demoting the primary was that the target's WAL receiver was active, meaning the streaming connection was up. It did not check how far behind the target was on WAL replay.
  3. The chosen replica could not be promoted until it finished replaying its backlog. In the operator, handlePromotion waits on waitForWalReceiverDown, which polls IsWALReceiverActive about once a second with no timeout. That WAL receiver only goes down once the old primary stops streaming to it.
  4. On the PostgreSQL side, the old primary's postmaster stayed in PM_SHUTDOWN_2 and kept its walsenders alive until the standbys were synced, so it kept streaming until the lagging replica caught up. The demotion runs pg_ctl stop with the timeout set to switchoverDelay (default 3600s), so it waits up to an hour for the walsenders to drain rather than failing fast.
  5. Promotion fired only when the target replica's WAL receiver finally dropped, about 14 minutes after the primary stopped accepting writes.

The cluster had no writable primary for roughly 14 minutes, entirely because the restart demoted the primary without first checking that a replica was caught up enough to take over. The switchover target is selected by received LSN, with replay LSN used only as a tiebreaker, and no absolute replay-lag threshold is applied anywhere in the rollout path. The single gate on the operation is whether the target's WAL receiver is active. A replica that has received almost all of the WAL but is far behind on applying it is therefore treated as a valid target. The operator has the information needed to make that call before it demotes the primary.

Preferable behavior

Before demoting the primary, a rolling restart or switchover should confirm that a viable promotion target exists, meaning a replica whose replay lag is low enough to be promoted quickly. If none exists, we would expect the operation to wait, or to fail with a clear error, instead of proceeding and leaving the cluster without a writable primary. This is close to how a Kubernetes Deployment rolling restart waits for new pods to become Ready before continuing. In our case every pod was Ready, but none was in a state to take over as leader.

Possible approaches
  1. Add a pre-flight check to the restart and switchover path that verifies the target replica's replay lag is below a threshold before demoting the primary.
  2. If no target is ready, block with an updated status condition and a clear message, and add a timeout so the operation fails loudly rather than silently holding the cluster without a primary.
  3. Offer an opt-out (a --force flag or annotation) for operators who knowingly accept the downtime. This also handles clusters that sit at a steady nonzero replay lag, where a hard threshold would otherwise never let a restart through.

I checked existing issues first. The closest are #9919 (replica-cluster designated-primary rollout blocked by an inactive WAL receiver, different scope), #9174 (interactive confirmation before cnpg destroy, different command), and #3680 (primary not shutting down gracefully, a symptom rather than the
promotion-readiness gap). None covers a restart or switchover demoting the primary without a caught-up promotion target.

I'm happy to work on/contribute to a fix if there's agreement on the general idea that a restart should be aware of the actual applied state beyond the cluster being Healthy/Not Healthy.

Cluster resource

Relevant log output

# Sharing a small excerpt of the logs, the timestamps don't really matter besides to illustrate the actual duration of cluster states

# demoted (old primary) instance — PostgreSQL logs (UTC)
16:09:46  received fast shutdown request
16:10:03  shutdown checkpoint complete
16:10:03..16:28:38  postmaster held in PM_SHUTDOWN_2, waiting on walsenders/archiver;
                    clients rejected: "the database system is shutting down" (SQLSTATE 57P03)
16:28:41  restarted, recovered as standby, rejoined on the new timeline

# operator logs (UTC)
16:23:41  promotion of target replica fired (its WAL receiver went down)

Code of Conduct

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

Activity

  1. added
    bug 🐛
    triage
    on Jul 1, 2026
  2. changed the title [-][Bug]:[/-] [+][Bug]: `cnpg restart` proceeds to switchover with an unpromotable (replay-lagged) replica[/+] on Jul 1, 2026
  3. dosubot commented on Jul 1, 2026

    @dosubot

    Hi @aleksandar-had! I'm Dosu and I'm helping the CloudNativePG team.

    Your analysis is accurate. I looked through the code and can confirm the behavior you're describing:

    Target selection uses PostgresqlStatusList.Less() which sorts replicas by received LSN first, with replay LSN only as a tiebreaker [1]. The rolling restart path then picks podList.Items[1] (the first replica in sorted order) as the switchover target [2].

    The only pre-demotion gate is the WAL receiver active check — the code verifies targetInstance.IsWalReceiverActive is true before proceeding, with the rationale that waitForWalReceiverDown on the promotion side can only work safely if streaming was active [3]. There is no replay lag threshold check anywhere in this path.

    After demotion, waitForWalReceiverDown polls pg_stat_wal_receiver every ~1 second with no timeout of its own [4]. Meanwhile the old primary's pg_ctl stop -m fast runs with the full switchoverDelay timeout (default 3600s) [5] [6], keeping walsenders alive until the standby catches up — exactly the 14-minute gap you observed.

    Related issues that touch adjacent concerns:

    Neither of these covers the specific gap you've identified: that a switchover/restart will demote the primary without verifying a replica is caught up on replay, not just on receive.

    Your proposed approaches (pre-flight replay-lag check, blocking with a status condition + timeout, and a force opt-out) all seem reasonable and well-aligned with the existing code structure — the operator already retrieves replayLSN during status collection, so the data is available at decision time.

    To reply, just mention @dosu.


    Docs are dead. Just use Dosu.

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

  4. ardentperf commented on Jul 2, 2026

    @ardentperf
    Contributor

    are you using sync replication? sync replication is key to ensuring no data loss on cnpg in quite a few different situations, including this one

  5. ardentperf commented on Jul 2, 2026

    @ardentperf
    Contributor

    see also #10783

  6. ardentperf commented on Jul 4, 2026

    @ardentperf
    Contributor

    i think the analysis in this issue also missed that promotion behavior differs depending on whether or not the target replica is streaming at the time of promotion (versus pulling from object storage)

    1. The primary got a fast shutdown and stopped accepting writes as soon as its shutdown checkpoint finished (under 30s). New connections were rejected with 57P03 ("the database system is shutting down").
    2. The rolling update selected the switchover target as the most advanced replica by received WAL position (podList.Items[1]). The only precondition it checked before demoting the primary was that the target's WAL receiver was active, meaning the streaming connection was up. It did not check how far behind the target was on WAL replay.

    postgres fast shutdown code has logic to drain unsent changes to streaming replicas that are connected, before it completes shutdown. normally targets are streaming - so this ensures that under normal operations any replica will receive all changes before they are promoted.

    1. All backends exit (PM_STOP_BACKENDS → PM_WAIT_BACKENDS)
    2. Checkpointer starts shutdown checkpoint
    3. Checkpointer finishes → sends PMSIGNAL_XLOG_IS_SHUTDOWN
    4. Postmaster (in PM_WAIT_XLOG_SHUTDOWN) receives signal
    5. Postmaster sends SIGUSR2 to all walsenders
       ↓
       [WALSENDER RECEIVES SIGUSR2]
       ↓
    6. Walsender calls WalSndDone():
       - Sends any outstanding WAL (including shutdown checkpoint record)
       - Waits for replicas to drain it (sentPtr == replicatedPtr)
       - Respects wal_sender_shutdown_timeout
       - Exits after WAL is confirmed or timeout expires
    

    https://github.com/postgres/postgres/blob/a8c2547eaac73cd6d499a4ab151f0401bf647f56/src/backend/postmaster/postmaster.c#L3860-L3883

    this is partly why i think sync replication is important; it generally helps throttle transactions to the rate required for providing high availability (making sure transactions are replicated before commit). as long as replicas are keeping up, they should continue streaming changes and they wont need to fall back to restoring from backups.

    also - the new 1.30 primary lease will make this even more robust by ensuring the shutdown completes (if possible) before promotion of the new replica.

    that being said, there might be a little room for making things more resilient in situations like a promotion getting triggered on a brand new replica that is still in the replay phase of its creation, or replicas that temporarily lost their streaming connection due to network instability or issues? we probably need to re-assess in light of the new primary lease design and figure out what still applies.

  7. aleksandar-had commented on Jul 6, 2026

    @aleksandar-had
    Author

    Thanks for the detailed dive, @ardentperf.

    We're not using sync replication, which was a conscious decision after experimenting with both sync, async replication and many postgres config tweaks due to the very specific use case and data flow patterns that this cluster was supposed to serve. FWIW, we've decided to go another way entirely after we reevaluated whether Postgres is even right tool for the job.

    Regardless, I think that in general the current state of clusters with async replication is that a lot of things are best effort when they might still have some room for safety.
    I get that choosing async replication comes with also choosing "potential data loss", but my suggestion stemmed from the fact that I couldn't imagine a situation where a restart leading to an unavailable cluster can be wanted.

    In the scenario I described, it would've been beneficial if the restart command actually waited for the replicas to actively replay enough WAL, so the shutdown and switch are fast enough to prevent a state of no-primary for multiple minutes.
    What you said was pretty much what I imagine:

    making things more resilient in situations like a promotion getting triggered on a brand new replica that is still in the replay phase of its creation, or replicas that temporarily lost their streaming connection due to network instability or issues

    I think the new primary lease (#10627) will improve correctness, but won't have a direct impact on the failure scenario that impacted the cluster, however, it can probably be used to make things more resilient against premature restarts.

    I'd be happy to contribute if there's agreement that such guardrails can be introduced to the restart command, lmk 👍

  8. gbartolini commented on Sep 14, 2026

    @gbartolini
    Contributor

    Thanks for the thorough write-up, @aleksandar-had. This is a real gap, separate from the failover/switchover work in #11357/#11358/#11367, that's about correctness; this one is about availability: we shouldn't demote a primary onto a replica that isn't caught up.

    Given how much is in motion in that area right now, I'd rather hold off here until the 1.31.0 patches land, then revisit with a clearer picture of what the primary lease gives us to build on.

    Also, a good concrete case for #10783 (sync replication by default), which narrows this window but doesn't remove the underlying gap.

  9. github-actions commented on Nov 17, 2026

    @github-actions
    Contributor

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

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