Repository navigation
Description
Existing issue / troubleshooting / supported version: [x] [x] [x]
Version: 1.30 (latest patch), 1.30.1 · Kubernetes: 1.35 · Environment: Other (self-managed) · Install: Helm
What happened?
Setup: 3-instance clusters, PostgreSQL 18 (18.6), WAL archiving through a CNPG-I plugin that implements the WAL service (isWALArchiver: true) and stores WAL in S3-compatible object storage. The clusters have a failover logical slot that a Debezium-style CDC client consumes (synchronizeLogicalDecoding: true). wal_sender_timeout=5s.
We ran an unsupervised rolling update (primaryUpdateMethod: switchover) over 78 clusters. Six of them ended with a replica permanently diverged from the new timeline, and CNPG still reported "Cluster in healthy state". No committed data was lost. The only WAL the broken replica had past the fork was the old primary's shutdown XLOG_SWITCH record.
Sequence (cluster A; T0 = old primary's received fast shutdown request; YY = segment, ZZ = YY+1):
- The shutdown checkpoint stalls. The checkpointer waits in
WalSndWaitStopping()for every walsender to exit. The logical walsender cannot exit because its client never confirms flush of the trailing non-transactional WAL; itsconfirmed_flush_lsnstays at the last commit. The physical walsenders also stop getting standby replies once shutdown starts (we do not know why), andwal_sender_timeoutreaps them at T+7.5 s. The logical walsender is reaped at T+9.5 s, and the shutdown checkpoint starts 40 ms later. - Both standbys stop at the same LSN, the end of the instance manager's pre-shutdown
CHECKPOINT(X/YY018E78). Neither receives theXLOG_SWITCHthatShutdownXLOGwrites before the shutdown checkpoint, because their streams are already gone. - The old primary archives segment YY with the
XLOG_SWITCHin it, in its final archiver cycle at T+11.10 s. It shuts down at T+11.46 s. This is the only old-timeline segment it archives, and it does so before any promotion. - The target promotes without that segment. Its
restore_commandattempt for YY started before the object existed and returned "not found" at T+10.95 s. At T+12.1 shandlePromotion()logs "applying WALs and promoting" and calls promote with no further restore attempt. PostgreSQL ends recovery at the end of the streamed WAL (redo done at X/YY018E00). Timeline N forks at X/YY018E78, before theXLOG_SWITCH. - The third replica restores the old-timeline segment and passes the fork. Its stream is gone too, so it falls back to
restore_command. At T+15.7 s it restores old-timeline segment YY, which contains theXLOG_SWITCH, and its recovery point moves to X/ZZ000000. That is 4.7 s before0000000N.historyexists in the archive, whilestatus.timelineIDis still N-1 andtargetPrimary != currentPrimary. From then on it is diverged for good. CNPGpg_rewinds the demoted old primary, so that one is fine, but nothing rewinds or re-clones the third replica.
The race. In all 78 switchovers the target was picked by the same logic.
- 68 clusters had no stall. The shutdown checkpoint came 0.05–0.7 s after the shutdown request, the standbys streamed the
XLOG_SWITCHand the shutdown checkpoint, and there was no problem. - 10 clusters stalled for 4.5–9.6 s. Every one of them had a logical walsender reaped by
replication timeout.- 6 diverged. For these, promote was decided 0.6–1.3 s after the final segment landed in the archive, and the target's last restore before promote was a miss decided between 0.15 s before and 1.2 s after the upload.
- 4 were fine. For these, the gap was 2.7–3.4 s, so the target restored segment YY, replayed the
XLOG_SWITCHand forked at X/ZZ000000. The third replica then consumed the same segment harmlessly (cluster B below).
In earlier rolling updates with primaryUpdateMethod: restart we saw the same stall, and replicas restored the same XLOG_SWITCH segment. That was harmless because no new timeline is created.
Expected behaviour
- Target side. Before promoting during a switchover, the target should replay all WAL the old primary produced up to its shutdown. For example, the old primary's instance manager could publish its final checkpoint LSN from
pg_controldataafter the clean shutdown, and the target would not promote until its replay LSN reaches it (fetching from the archive). At minimum, it should retryrestore_commandfor the next segment on the current timeline for a bounded time before calling promote. Whether "the shutdown streamed everything" holds should be checked rather than assumed. That also applies to the precondition proposed in [Feature]: Skip archive lookups that cannot succeed when the target of a planned switchover promotes #11638. - Non-target replicas. While a switchover is in progress (
targetPrimary != currentPrimary, or a pending marker as in PR Fix race condition in primary update switchover #11185),wal-restoreshould not serve WAL segments of the old timeline. The replica should wait and stream from the new primary instead. - Health. A replica that logs "forked off current database system timeline … before current recovery point" or "not in this server's history" should not count as healthy, and an unsupervised rolling update should stop. This is the [Bug]: Replica permanently stuck in wal-restore loop after failover: walreceiver never reconnects, operator reports cluster healthy, burns CPU indefinitely #10419 / [Bug]: Replica does not come up: checkpoint not found in timeline #4990 class.
Reproduction (derived from production evidence; not yet reproduced in isolation)
- Create a 3-instance cluster on PG 18 with
wal_level=logical,wal_sender_timeout=5s,wal_receiver_timeout=5sandhot_standby_feedback=on. SetreplicationSlots.highAvailability.synchronizeLogicalDecoding: true(CNPG then setssynchronized_standby_slots). Archive WAL through a CNPG-I WAL archiver plugin to object storage. - Create a logical slot with
failover = true(pgoutput). Attach a client that only reportsflush_lsnup to the last COMMIT it received, as Debezium does. A psycopg2LogicalReplicationConnectionconsumer that callssend_feedback(flush_lsn=<commit lsn>)only on commit messages is enough. A light write load is optional. - Trigger a switchover. We used an unsupervised primary update;
kubectl cnpg promoteuses the samehandlePromotion()path but is untested here. - On the old primary, confirm that "checkpoint starting: shutdown" comes about
wal_sender_timeoutafter "received fast shutdown request". Then check the non-target replica for "restored log file "…YY" from archive" followed by the fork errors. Repeat if needed: the outcome depends on 1–3 s of timing (6 of 10 stalls diverged for us).
Cluster resource (relevant parts)
spec:
instances: 3
imageCatalogRef: { kind: ClusterImageCatalog, major: 18 }
primaryUpdateStrategy: unsupervised
primaryUpdateMethod: switchover
plugins:
- name: <cnpg-i-wal-archiver-plugin>
isWALArchiver: true
replicationSlots:
highAvailability: { enabled: true, synchronizeLogicalDecoding: true }
synchronizeReplicas: { enabled: true }
postgresql:
synchronous: { method: any, number: 1, dataDurability: required } # also seen on a cluster without synchronous
parameters:
wal_level: logical
archive_timeout: 5min
hot_standby_feedback: "on"
sync_replication_slots: "on"
wal_sender_timeout: 5s
wal_receiver_timeout: 5sRelevant log output
# Cluster A (diverged). A-1 = old primary, A-2 = target, A-3 = third replica. archive = object-store LastModified.
T-0.01 A-1 Executing CHECKPOINT command before shutdown (checkpoint complete … redo X/YY018E00)
T+0.00 A-1 received fast shutdown request
T+7.50 A-1 terminating walsender process due to replication timeout (application_name=A-2)
T+7.50 A-1 terminating walsender process due to replication timeout (application_name=A-3)
T+9.51 A-1 terminating walsender process due to replication timeout (application_name=Debezium Streaming)
T+9.56 A-1 checkpoint starting: shutdown immediate (XLOG_SWITCH at X/YY018E78, ckpt X/ZZ000028)
T+10.95 A-2 restore_command: <old TL>…YY not found in archive
T+11.10 archive <old TL>…YY created (old primary's final archiver cycle)
T+11.46 A-1 database system is shut down
T+11.47 A-3 record with incorrect prev-link … at X/YY018E78
T+12.11 A-2 I'm the target primary, applying WALs and promoting my instance
T+13.08 A-2 record with incorrect prev-link … at X/YY018E78 ; received promote request ; redo done at X/YY018E00
T+15.74 A-3 restored log file "<old TL>…YY" from archive
T+17.82 A-2 selected new timeline ID: N
T+19.53 A-3 unexpected pageaddr … in WAL segment <old TL>…ZZ, LSN X/ZZ000000, offset 0
T+20.43 archive 0000000N.history created
T+28.7 A-3 FATAL: could not start WAL streaming: ERROR: requested starting point X/ZZ000000 on timeline N-1 is not in this server's history
DETAIL: This server's history forked from timeline N-1 at X/YY018E78.
T+31.4 A-3 new timeline N forked off current database system timeline N-1 before current recovery point X/ZZ000000 (loops until re-clone)
# Cluster B (stalled, survived): the target restored the segment before promote, so the fork is at the segment boundary.
T+4.42 B-2 terminating walsender process due to replication timeout (Debezium Streaming) ; T+4.46 checkpoint starting: shutdown
T+~5.3 B-2 final segment <old TL>…YY archived
T+7.99 B-1 I'm the target primary, applying WALs and promoting my instance
T+9.14 B-1 restored log file "<old TL>…YY" from archive ; T+9.92 B-3 restored the same segment
T+11.67 B-1 unexpected pageaddr … LSN X/ZZ000000 ; received promote request ; redo done at X/YY00ADF8
T+26.1 B-3 started streaming WAL from primary at X/ZZ000000 on timeline NRelated (why these are not the same)
- [Bug]: Potential race condition in primary update switchover #11114 / PR Fix race condition in primary update switchover #11185. These cover the streaming variant: writes made between target selection and shutdown reach the third replica but not the target. Here both standbys had identical streamed end LSNs, and the extra record came from the archive. Picking the most advanced replica after the WAL receivers stop (Fix race condition in primary update switchover #11185) is a tie in this case, and the winner still promotes without the archived segment.
- PR fix: prevent replicas from restoring old-timeline WAL segments #10394. It rejects old-timeline segments only when
walTimeline < status.timelineID. Its extra guard applies only toPendingFailoverMarker. Here the fetch happened whilestatus.timelineIDwas still N-1 andtargetPrimarywas a pod name, so neither check fires. Extending the guard to "switchover in progress" would cover the replica side. - After primary SIGKILL, CNPG promotes a replica that is not the most advanced one, causing timeline divergence on other replicas #11557 is a failover after SIGKILL that promotes a less-advanced replica (streaming). [Bug]: Replica permanently stuck in wal-restore loop after failover: walreceiver never reconnects, operator reports cluster healthy, burns CPU indefinitely #10419 / [Bug]: Replica does not come up: checkpoint not found in timeline #4990 are the downstream symptom: a stuck loop while the cluster reports healthy.
Workaround
- Stop the logical client before a switchover and check that
pg_stat_replicationhas no logical walsender. The shutdown then takes about 0.1 s and the standbys stream theXLOG_SWITCHand the shutdown checkpoint. - Alternatively, use
primaryUpdateMethod: restartfor clusters with CDC clients. - Recovery: re-clone the diverged replica.
- On the PostgreSQL side, the proposed
wal_sender_shutdown_timeoutGUC (pgsql-hackers, not in PG 18) would bound the stall.
Activity
chobostar commentedon Oct 29, 2026
Re "The physical walsenders also stop getting standby replies once shutdown starts (we do not know why)": we hit
the same thing on 1.30.0 and found the cause in our environment. Which CNI do you run, and do replicas reach the
primary through
<cluster>-rw?Since #10409 (in 1.29.1 and 1.30.x) the reconcile guard relabels the old primary
cnpg.io/instanceRole=unhealthywhenever
CurrentPrimary != TargetPrimary, so also at the very start of a switchover, while the old primary isstill running CHECKPOINT and streaming.
-rwloses its only backend. Replicas stream through-rw(
primary_conninfo host=<cluster>-rw). With kube-proxy the established flows survive via conntrack. With Ciliumkube-proxy replacement without socket LB (
bpf-lb-sock=false) the VIP is translated per packet, so establishedreplica connections go silent both ways and are reaped by
wal_sender_timeout/wal_receiver_timeout.The #10409 description assumes the opposite ("does not drop TCP connections already established by a replica's
walreceiver").
Production, 2 days: 8
replication timeoutdisconnects, each ~5 s after a switchover started, all on our onlyCilium cluster; 42 switchovers on a kube-proxy cluster with the same operator: 0. Two incidents with a permanently
diverged replica. Reproduced on a test cluster (pgbench,
kubectl cnpg promote): label changed at 13:40:32.8,Cilium had 0 backends for
-rwby 13:40:34.4, the old primary's fast shutdown started only at 13:40:34.2, bothends timed out at 13:40:38.5. Hubble later showed a packet of the old connection redirected to the new backend
and answered with RST.
In our case the target and the other replica then raced for the shutdown checkpoint over streaming (the update
reaches each node at a different time) rather than via the archive as in your cluster A, but the start is the same:
the streams die before
ShutdownXLOG. Keeping the old primary labelled until it has shut down during aswitchover (applying #10409 only to failover) would remove this trigger; your target-side and health items would
still be needed for the other paths.
antoinemichea commentedon Nov 3, 2026
We hit the same end state on 1.27.0 after a failover (not a switchover), and the diverged reader was a replica cluster that follows the object store. We're adding our timeline because the post-fork WAL came from a different path than in your report. The old primary wrote it after the operator had already decided the failover, while that primary was coming back from a crash.
Setup
isWALArchiver: true), PostgreSQL 17.5, Kubernetes 1.35.2, containerd 2.3.3, cgroup v2.replicationSlots.highAvailabilityenabled,archive_timeout: 5min,wal_sender_timeout/wal_receiver_timeout: 5s,failoverDelay: 0.Clusterwithreplica.enabled: true, 1 instance (R-1). ItsexternalClusterspoint to the same object store through the plugin (isWALArchiver: false). It has no streaming connection to the source and only follows the archive.Trigger
The cgroup OOM killer sent SIGKILL to a single backend on A-1. Because
restart_after_crashis off, the postmaster exited, and the container restarted about 3 s later.Timeline
T0 is the last commit on timeline N-1 (record at X/YY5880E0, ending at X/YY588110).
could not receive data from WAL stream: SSL SYSCALL error: EOF detectedrecord with incorrect prev-link … at X/YY588110: the end of the streamed WAL, which later becomes the fork pointpostmaster started, as a primary: no standby.signal, and the cluster status still names it current primaryCannot extract Pod status … the database system is starting upCurrent primary isn't healthy, initiating a failoverFailing over(newPrimary A-3)redo done at X/YY5880E0checkpoint starting: end-of-recovery immediate waitwrites CHECKPOINT_SHUTDOWN at X/YY588110I'm the target primary, applying WALs and promoting my instancedatabase system is ready to accept connections, as a read-write primary on N-1received promote request,redo done at X/YY5880E0restore_commandfor N-1 segment YY: not foundThis is an old primary node. Requesting a checkpoint before demotionwrites CHECKPOINT_REDO, RUNNING_XACTS, CHECKPOINT_ONLINEShutting it down to get it demoted to a replica, fast shutdown;ShutdownXLOGwrites XLOG_SWITCH at X/YY588258selected new timeline ID: Ndatabase system is shut downserver promoted0000000N.history(in the store at +8.98) and…YY.partialRestoring WAL fileN-1 segment YY: restored and replayed up to X/ZZ000000Setting replica labelA-1,Setting primary labelA-3pg_rewind: servers diverged at WAL location X/YY588110 on timeline N-1, rewound finenew timeline N forked off current database system timeline N-1 before current recovery point X/ZZ000000, thenwaiting for WAL to become available at X/ZZ000018. This went on for about 14 h, while the replica cluster stayed inCluster in healthy stateTimeline history file:
N-1 X/YY588110 no recovery target specified.pg_waldumpon the N-1 segment that R-1 restored:No transaction follows the fork. No committed data was lost, and nothing was written on A-1 during the ~0.8 s it accepted connections.
Differences with the original report
XLOG_SWITCH. Its own archiver then uploaded it, 1.3 s after the operator had picked the new target.targetPrimary/currentPrimary, so a guard on non-target replicas (your expected behaviour 2) would not protect it. Only the writing side can.0000000N.historywas in the store 86 ms before R-1's next attempt. R-1's polling cycle asks for the next segment on its current timeline before it looks for a newer history file (its log shows segment, then history, every ~5 s), so the N-1 segment won.What would have prevented it in our case
targetPrimarycould refuse to archive:wal-archiveor the CNPG-I archive call returns an error, the files stay.ready, andpg_rewinddiscards them anyway. All of our post-fork WAL left through A-1's archiver.forked off … before current recovery pointshould not report healthy, which matches your expected behaviour 3. We only noticed through a replication-lag alert.Side note: A-1 accepted connections from T+5.76 to T+6.57 s while it still carried the primary label, which the operator only changed at T+10.43. The startup probe (10 s period) most likely kept it out of the
-rwendpoints, and nothing was written, but the window exists.Recovery: we re-created the replica cluster from a VolumeSnapshot of the rewound standby, and it picked up timeline N from the archive. The polluted N-1 segment stays in the object store. As far as we can tell, a recovery that starts once
0000000N.historyexists tries the timeline N segment first, so restores are not affected.We can share more logs if that helps.
feat(failover): detect and contain a replica that diverged from the p…
feat(failover): detect and contain a replica that diverged from the p…