Repository navigation
Description
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
Version
1.28 (latest patch)
What version of Kubernetes are you using?
1.33
What is your Kubernetes environment?
Self-managed: kind (evaluation)
How did you install the operator?
YAML manifest
What happened?
Description
We hit a production incident where failover was blocked for ~45 minutes because the walsender on the old primary kept running after a storage failure. The node's NVMe died but the kernel and network stayed alive (on-prem hypervisor). The walsender doesn't need disk I/O in its steady-state loop, it reads WAL from shared memory and sends keepalives over TCP. These keepalives kept the replicas' WAL receivers connected, preventing the AreWalReceiversDown gate from clearing.
What's happening
After a storage failure where the kernel stays alive:
- PostgreSQL backends freeze on disk I/O
- The walsender keeps running and sending keepalives every
wal_sender_timeout / 2(~30s) - WAL receivers receive keepalives, resetting
wal_receiver_timeouteach time, so the timeout never fires wal_receiver_timeoutis unlikely to help. The WAL receiver solicits keepalives via therequestReplyflag at half-timeout (walreceiver.c:581), the walsender responds immediately, resetting the timer before the full timeout fires- Operator detects unhealthy primary, sets
TargetPrimary = PendingFailoverMarker - Old primary's instance manager receives the signal but can't shut down PostgreSQL because the checkpoint blocks on disk I/O, so the walsender never gets SIGTERM
AreWalReceiversDownreturns false on every reconcile loop, failover blocked indefinitely
Reproduction
Reproduced in a local kind cluster with CNPG 1.28.2.
3-instance cluster across 3 kind worker nodes. To simulate the zombie node:
- SIGSTOP the kubelet on the primary's node (prevents pod restart)
- SIGSTOP the instance manager (PID 1) and postmaster inside the primary pod via
crictl exec - Leave walsenders running (they don't need disk I/O)
After ~9 minutes (node NotReady + taint eviction), walsenders are still running:
༼ つ ▀_▀ ༽つ ~ src timelines docker exec zombie-test-worker crictl exec 360b3c2bdd122 ps aux | grep walsender
postgres 336 0.0 0.1 227652 9284 ? Ss 13:42 0:00 postgres: zombie-test: walsender streaming_replica 10.244.3.8(44426) streaming 0/7000110
postgres 578 0.0 0.1 227692 9248 ? Ss 13:43 0:00 postgres: zombie-test: walsender streaming_replica 10.244.2.9(45238) streaming 0/7000110
WAL receivers on replicas still connected:
༼ つ ▀_▀ ༽つ ~ src timelines kubectl exec zombie-test-2 -c postgres -- psql -tAc "SELECT count(*) FROM pg_stat_wal_receiver;"
1
Operator detects unhealthy primary but gets stuck:
{"ts":"2026-04-29T13:51:47Z","msg":"Current primary isn't healthy, initiating a failover"}
{"ts":"2026-04-29T13:51:47Z","msg":"Waiting for all WAL receivers to be down to elect a new primary"}
That last line repeats indefinitely.
Also reproduced the keepalive behavior in plain Docker without CNPG: PG 13 primary + streaming replica with wal_receiver_timeout=15s and zero write activity. WAL receiver stays connected for 90s+ because the walsender sends keepalives. Killing the walsender causes instant disconnection.
Happy to share the full reproduction scripts if useful.
What we tried
There are two gates in the failover path that both block indefinitely:
-
Operator controller (replicas.go:147):
AreWalReceiversDownchecks if all replicas' WAL receivers have disconnected before electing a new primary. -
Instance manager (instance_controller.go:1195):
waitForWalReceiverDownwaits for the replica's own WAL receiver to shut down before promoting. UsesSteps: math.MaxInt32and the error from timeout causeshandlePromotionto retry indefinitely.
We patched both locally and tested end-to-end:
For replicas.go: during failover (TargetPrimary == PendingFailoverMarker), if the gate has been blocking for >40s, skip it. Switchover behavior unchanged.
For instance_controller.go: changed Steps: math.MaxInt32 to Steps: 40. In handlePromotion, proceed with promotion despite timeout error instead of retrying.
With both changes, full automated failover completes:
21:35:35 — Frozen (kubelet + instance manager + postmaster SIGSTOP'd, walsenders alive)
21:37:55 — Gate 1 bypassed: "proceeding with failover anyway"
21:37:55 — "Failing over, newPrimary: zombie-test-2"
21:38:37 — Gate 2 bypassed: "Proceeding with promotion despite WAL receiver still active"
21:38:37 — "applying WALs and promoting my instance"
21:39:36 — "Setting primary label" → zombie-test-2. Failover complete.
Without the changes, gate 1 repeated 2,423 times and gate 2 repeated 1,499 times with no progress.
Trade-offs and open questions
The hard timeout approach works but has trade-offs we'd like input on.
Both gates exist to protect against data loss during switchover when real WAL is actively streaming. We picked 40s arbitrarily as something that felt conservative enough. WAL receivers disconnect in <1s during normal switchover, so 40s leaves a lot of room. But a hard timeout could theoretically cut off in-flight WAL if something legitimately delays WAL receiver shutdown for >40s.
A potentially smarter approach: the operator already queries each replica's WAL receiver status every reconcile loop via IsWalReceiverActive which checks pg_stat_wal_receiver. Extending this to also track received_lsn across iterations would give a cleaner signal. If last_msg_receipt_time advances but received_lsn stays the same, only keepalives are flowing and there's no real WAL data to protect. This would distinguish "zombie node, nothing will ever come" from "wait, real data is still arriving."
Our local fix also uses a package-level variable to track the gate timeout which doesn't work well with multiple clusters. A proper implementation would need per-cluster state.
Would appreciate thoughts on the right approach here. Happy to contribute a PR if there's alignment on direction.
Environment
CNPG 1.28.2, PostgreSQL 13 in production, 18 in kind reproduction. On-prem with NVMe storage (production), kind on macOS (reproduction).
Related
- [Bug]: Replica permanently stuck in wal-restore loop after failover: walreceiver never reconnects, operator reports cluster healthy, burns CPU indefinitely #10419
- fix: auto-recover replicas with diverged timelines by re-cloning #9637
- [Bug]: Replica does not come up: checkpoint not found in timeline #4990
Cluster resource
Relevant log output
Code of Conduct
- I agree to follow this project's Code of Conduct
Metadata
Metadata
Assignees
Type
Projects
- StatusShow more project fieldsDone
Activity
dosubot commentedon May 1, 2026
This is a well-documented report. A few things to add from code and issue research:
Directly related prior work: Issue #10419 [1] reports a very similar class of failure — a demoted primary stuck for 40+ hours in an infinite WAL-restore loop because the WAL receiver was down, while the operator reported the cluster as fully healthy. That issue also identifies the same
IsWALReceiverActivemonitoring gap and proposes a WAL receiver health watchdog with escalation (restart → pg_rewind → manual intervention). You may want to coordinate with that effort.On the two gates you patched:
AreWalReceiversDowninreplicas.go— the errorErrWalReceiversRunningcauses a 1-second requeue loop indefinitely [2]. As you identified, there is no timeout or staleness detection.waitForWalReceiverDownininstance_controller.go— theRetryUntilWalReceiverDownbackoff is configured withSteps: math.MaxInt32and a fixed 1-secondDurationwith no factor/jitter, so it's effectively an infinite 1-second polling loop [3]. The comment in the code acknowledges "This is not really exponential backoff" [4].On your LSN-based approach: Your idea of tracking
received_lsnacross iterations to distinguish keepalive-only traffic from real WAL streaming is sound, but currently no LSN history is persisted across reconcile loops —CurrentLsn,ReceivedLsn, andReplayLsnare all collected fresh each cycle with no historical comparison [5]. Implementing this would require adding per-cluster state tracking (as you noted).Recent related improvements worth noting:
tcp_user_timeoutfor standby replication connections was changed from the system default (~127s) to 5s to detect silent network drops faster, but this doesn't help when keepalives are actively flowing as in your scenariowalRestoreRetryTimeoutfor transient WAL restore failuresYour zombie-node scenario is distinct from the timeline-divergence cases in that the walsender stays alive and actively prevents the timeout from firing. The LSN-stale-detection approach or a hard timeout with a conservative threshold both seem like reasonable directions — the hard timeout is simpler but less precise, while LSN tracking is more surgical but requires new per-cluster state.
To reply, just mention @dosu.
Share context across your team and agents. Try Dosu.
fix(instance): promote a candidate whose WAL receiver is stalled on a…
github-actions commentedon Aug 21, 2026
This issue is stale because it has been open for 60 days with no activity.
3 remaining items
gbartolini commentedon Sep 14, 2026
Thanks, @daanvinken, for the detailed write-up and reproduction (and the solid analysis).
Quick status update: rather than patching this gate (and the related ones) individually, we've taken a step back now that CloudNativePG has the Kubernetes
Leaseobject as a single source of truth for who's primary. We're using that to redesign the failover/switchover coordination logic itself, rather than adding more timeouts on top of WAL-receiver state.This turned into a small cluster of issues and PRs:
RetryPeriod): fixed, merged, backporting to 1.30.z.And the core rework, which is not being backported and will ship in 1.31:
None of the 1.31 PRs has been merged yet; #11367, in particular, still needs two more reviews, so I can't give you a firm date. This is active, and the direction is set. I'll follow up here once 1.31 has a release candidate.
mnencia commentedon Nov 3, 2026
Thanks @daanvinken for the report, the repro and the offer to contribute. It led to a rework of the failover path, now on main and shipping in 1.31, which has no release candidate yet.
The WAL receiver wait stays. We dropped the plan to remove it (#11367, which also carried the fix for #11346): it still protects WAL during switchover, manual promotion and upgrades from older instance managers. The #11346 fix landed separately in #11336. What changed is that the old primary now gets stopped, so the wait ends. During a failover its instance manager stops PostgreSQL, going straight to an immediate shutdown when PostgreSQL does not answer (#11347). If PostgreSQL ignores that for
.spec.immediateShutdownTimeout(30s by default), the liveness probe fails and the kubelet restarts the container (#11358). Either way the walsenders die and the receivers drop. A primary that cannot renew its lease (#11357) also stops itself, after checking its peers.Your production case (dead disk, kernel and kubelet alive) is covered: the instance manager is alive there, so the immediate shutdown reaches the walsenders, and if PostgreSQL hangs on it the liveness restart takes over. A hard timeout or received_lsn tracking on the gates is not needed. Only #11347 and #11336 are backported to 1.30, the rest ships in 1.31.
Your SIGSTOP repro freezes the kubelet and the instance manager together. The step-down needs the instance manager and the liveness restart needs the kubelet, so nothing can stop the walsenders and the failover waits. It takes both hanging at once, which is a rare combination. We reproduced it on kind with a build of main. With the kubelet systemd watchdog enabled and
.spec.probes.liveness.terminationGracePeriodSeconds: 30, systemd restarts the kubelet, the liveness probe fails and the container is killed. The failover then completed in under 90 seconds. Without the short grace period, the kill waits for the pod grace period (30 minutes by default). The lease prevents a second primary throughout. #11838 documents this and closes the issue.daanvinken commentedon Nov 3, 2026
Amazing, thanks @mnecia for circling back
docs(failover): explain hung kubelet and instance manager case
docs(failover): explain hung kubelet and instance manager case
docs(failover): explain hung kubelet and instance manager case (cloud…