Skip to content

[Bug]: Failover blocked indefinitely when walsender survives on zombie node (storage failure with kernel alive) #10591

Description

@daanvinken

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

  1. PostgreSQL backends freeze on disk I/O
  2. The walsender keeps running and sending keepalives every wal_sender_timeout / 2 (~30s)
  3. WAL receivers receive keepalives, resetting wal_receiver_timeout each time, so the timeout never fires
  4. wal_receiver_timeout is unlikely to help. The WAL receiver solicits keepalives via the requestReply flag at half-timeout (walreceiver.c:581), the walsender responds immediately, resetting the timer before the full timeout fires
  5. Operator detects unhealthy primary, sets TargetPrimary = PendingFailoverMarker
  6. 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
  7. AreWalReceiversDown returns 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:

  1. SIGSTOP the kubelet on the primary's node (prevents pod restart)
  2. SIGSTOP the instance manager (PID 1) and postmaster inside the primary pod via crictl exec
  3. 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:

  1. Operator controller (replicas.go:147): AreWalReceiversDown checks if all replicas' WAL receivers have disconnected before electing a new primary.

  2. Instance manager (instance_controller.go:1195): waitForWalReceiverDown waits for the replica's own WAL receiver to shut down before promoting. Uses Steps: math.MaxInt32 and the error from timeout causes handlePromotion to 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

Cluster resource

Relevant log output

Code of Conduct

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

Activity

  1. added
    triage
    on May 1, 2026
  2. dosubot commented on May 1, 2026

    @dosubot

    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 IsWALReceiverActive monitoring 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:

    1. AreWalReceiversDown in replicas.go — the error ErrWalReceiversRunning causes a 1-second requeue loop indefinitely [2]. As you identified, there is no timeout or staleness detection.

    2. waitForWalReceiverDown in instance_controller.go — the RetryUntilWalReceiverDown backoff is configured with Steps: math.MaxInt32 and a fixed 1-second Duration with 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_lsn across iterations to distinguish keepalive-only traffic from real WAL streaming is sound, but currently no LSN history is persisted across reconcile loops — CurrentLsn, ReceivedLsn, and ReplayLsn are 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:

    • PR #9650 and PR #9849 added timeline validation to prevent replicas from restoring future timeline history files
    • PR #10394 (open) proposes rejecting old-timeline WAL segments to force streaming replication
    • The tcp_user_timeout for 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 scenario
    • PR #10552 (open) proposes a walRestoreRetryTimeout for transient WAL restore failures

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

    Leave Feedback Learn about cloudnative-pg with Dosu Add Dosu to your team

  3. added
    bug 🐛
    and removed on Jun 21, 2026
  4. added 3 commits that reference this issue on Jul 28, 2026
    8e26535
  5. github-actions commented on Aug 21, 2026

    @github-actions
    Contributor

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

  6. 3 remaining items

  7. removed
    triage
    on Sep 14, 2026
  8. added this to the 1.31.0 milestone on Sep 14, 2026
  9. gbartolini commented on Sep 14, 2026

    @gbartolini
    Contributor

    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 Lease object 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:

    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.

  10. mnencia commented on Nov 3, 2026

    @mnencia
    Member

    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.

  11. daanvinken commented on Nov 3, 2026

    @daanvinken
    ContributorAuthor

    Amazing, thanks @mnecia for circling back

  12. added a commit that references this issue on Nov 9, 2026
    5d276e6
  13. added a commit that references this issue on Nov 10, 2026
    e930779
  14. added a commit that references this issue on Nov 10, 2026
    fd13e85
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug 🐛no-stale

Type

Projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions