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
older in 1.28.x
What version of Kubernetes are you using?
1.34
What is your Kubernetes environment?
Other
How did you install the operator?
Helm
What happened?
We're experiencing data loss when restoring from WAL archives after hibernating a CNPG cluster that uses plugin-barman-cloud. The last WAL segment does not appear to be archived to S3 during shutdown. The same scenario works as expected with in-tree barmanObjectStore.
Steps to reproduce
- Create a CNPG cluster with
plugin-barman-cloudconfigured for WAL archiving to S3, let it run for a while, WAL archiving is working correctly - Backup the database to S3
- Insert data into the database (for timestamping purposes)
- Hibernate the cluster
- Create a new cluster restoring from the WAL archive of the hibernated one
- The most recent data written before hibernation is missing — the last WAL segment was never archived to S3
The same steps using in-tree barmanObjectStore instead of the plugin work correctly — all data is recovered.
Observations
-
Native sidecar ordering: We've confirmed from the actual pod spec that plugin-barman-cloud is deployed as a Kubernetes native sidecar (initContainers with restartPolicy: Always). Our clusters run K8s 1.33.8 and 1.34.4, where native sidecar lifecycle guarantees are GA. The kubelet will not send SIGTERM to the sidecar until after the postgres container has fully exited.
-
preStop hooks: We've seen recommendations to look at adding a hook to run
pg_switch_walviacnpg.io/podPatchannotation. This feels a bit fragile as dependent on index of containers to attach this to the correct container. -
Possible Root cause: We believe the actual root cause is that
ArchiveAllReadyWALs()(in archiver.go:63-120) is only called during switchover/demotion (instance_startup.go:129), not during normal pod termination. AfterTryShuttingDownSmartFast()returns in lifecycle.go:148, the instance manager exits without sweeping remaining.readyWAL files -- even though the native sidecar is still alive and could handle the gRPC calls. Can you confirm whether this gap has been identified and whether there are plans to address it?
Environment
- CNPG Operator version: v1.28.0
- Plugin barman-cloud version: v0.10.0
- running as a native sidecar (therefore doesn't get SIGTERM on initial shutdown of the pod)
- Kubernetes version: v1.34.4
- PostgreSQL 16
Cluster resource
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
annotations:
argocd.argoproj.io/sync-app: "-50"
argocd.argoproj.io/tracking-id: appinstance-0123456789a:postgresql.cnpg.io/Cluster:appinstance-0123456789a/postgresql
labels:
app.kubernetes.io/component: db
app.kubernetes.io/instance: appinstance-0123456789a
app.kubernetes.io/managed-by: Helm
app.kubernetes.io/name: postgresql
app.kubernetes.io/part-of: helm-app
app.kubernetes.io/version: 1.0.0
app.acmefirm.com/manifest: "manifest-0123456789a"
app.acmefirm.com/appCategory: internal
app.acmefirm.com/appName: "0123456789a"
app.acmefirm.com/appUuid: 0123456789a
app.acmefirm.com/tier: dev
helm.sh/chart: postgresql-3.0.0
name: postgresql
namespace: appinstance-0123456789a
spec:
affinity:
nodeSelector:
node-asg: apps
podAntiAffinityType: required
tolerations:
- effect: NoSchedule
key: node-asg
operator: Equal
value: apps
topologyKey: topology.kubernetes.io/zone
bootstrap:
initdb:
database: app
encoding: UTF8
localeCType: C
localeCollate: C
owner: app
postInitApplicationSQLRefs:
configMapRefs:
- key: sql
name: postgresql-init-script
description: The database cluster of the app application
enablePDB: true
enableSuperuserAccess: false
failoverDelay: 0
imageCatalogRef:
apiGroup: postgresql.cnpg.io
kind: ImageCatalog
major: 16
name: postgresql-image-catalog
imagePullPolicy: IfNotPresent
inheritedMetadata:
annotations:
cluster-autoscaler.kubernetes.io/safe-to-evict: "false"
labels:
app.kubernetes.io/component: db
app.kubernetes.io/instance: appinstance-0123456789a
app.kubernetes.io/managed-by: Helm
app.kubernetes.io/name: postgresql
app.kubernetes.io/part-of: helm-app
app.kubernetes.io/version: 1.0.0
app.acmefirm.com/manifest: "manifest-0123456789a"
app.acmefirm.com/node-group: apps
app.acmefirm.com/appCategory: internal
app.acmefirm.com/appName: "0123456789a"
app.acmefirm.com/appUuid: 0123456789a
app.acmefirm.com/tier: dev
helm.sh/chart: postgresql-3.0.0
monitoring.acmefirm.com/enabled: "true"
networking.acmefirm.com/allow-api-server-access: "true"
networking.acmefirm.com/allow-external-egress-access: "true"
networking.acmefirm.com/allow-postgresql-access: "true"
instances: 3
logLevel: debug
managed:
roles:
- comment: App Read only user
connectionLimit: -1
ensure: absent
inRoles:
- pg_read_all_data
inherit: true
login: true
name: app_ro
maxSyncReplicas: 1
minSyncReplicas: 1
monitoring:
customQueriesConfigMap:
- key: queries
name: cnpg-default-monitoring
- key: custom-metrics
name: postgresql-custom-metrics
disableDefaultQueries: false
enablePodMonitor: true
podMonitorRelabelings:
- action: replace
sourceLabels:
- __meta_kubernetes_pod_label_cnpg_io_instanceName
targetLabel: cnpg_instance_name
- action: replace
sourceLabels:
- __meta_kubernetes_pod_label_cnpg_io_instanceRole
targetLabel: cnpg_instance_role
plugins:
- enabled: true
isWALArchiver: true
name: barman-cloud.cloudnative-pg.io
parameters:
barmanObjectName: postgresql-backup
postgresGID: 26
postgresUID: 26
postgresql:
parameters:
archive_mode: "on"
archive_timeout: 5min
auth_delay.milliseconds: "500"
dynamic_shared_memory_type: posix
full_page_writes: "on"
hot_standby_feedback: "true"
log_destination: csvlog
log_directory: /controller/log
log_filename: postgres
log_rotation_age: "0"
log_rotation_size: "0"
log_truncate_on_rotation: "false"
logging_collector: "on"
max_connections: "1000"
max_parallel_workers: "32"
max_replication_slots: "32"
max_slot_wal_keep_size: 3891MB
max_wal_size: 1GB
max_worker_processes: "32"
pg_failover_slots.synchronize_slot_names: slot_for_data_gateway_changefeed_replication
pg_stat_statements.max: "5000"
pg_stat_statements.save: "false"
pg_stat_statements.track: all
pg_stat_statements.track_planning: "false"
pg_stat_statements.track_utility: "true"
shared_memory_type: mmap
shared_preload_libraries: ""
ssl_max_protocol_version: TLSv1.3
ssl_min_protocol_version: TLSv1.3
track_io_timing: "on"
wal_keep_size: 512MB
wal_level: logical
wal_log_hints: "on"
wal_receiver_timeout: 5s
wal_sender_timeout: 5s
pg_hba:
- hostssl app streaming_replica all cert
promotionTimeout: 8
shared_preload_libraries:
- auth_delay
syncReplicaElectionConstraint:
enabled: false
primaryUpdateMethod: restart
primaryUpdateStrategy: unsupervised
priorityClassName: app-non-premptible
probes:
liveness:
isolationCheck:
connectionTimeout: 1000
enabled: true
requestTimeout: 1000
replicationSlots:
highAvailability:
enabled: true
slotPrefix: _cnpg_
synchronizeReplicas:
enabled: true
updateInterval: 30
resources:
limits:
cpu: "6"
memory: 2400Mi
requests:
cpu: 100m
memory: 800Mi
serviceAccountTemplate:
metadata:
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::987654321234:role/dev-0123456789a-role
smartShutdownTimeout: 180
startDelay: 3600
stopDelay: 1800
storage:
pvcTemplate:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
storageClassName: postgresql-data-gp3-appinstance-0123456789a
resizeInUseVolumes: true
switchoverDelay: 3600Relevant log output
Code of Conduct
- I agree to follow this project's Code of Conduct
Activity
dosubot commentedon Mar 19, 2026
Hi @aglees! I'm Dosu and I’m helping the cloudnative-pg team.
Your analysis is correct.
ArchiveAllReadyWALs()is only called during instance startup, not during shutdown. AfterTryShuttingDownSmartFast()returns, the instance manager exits without sweeping remaining.readyWAL files.This issue affects both plugin-barman-cloud and in-tree barmanObjectStore (there's a related open issue tracking this). A CHECKPOINT was added before shutdown in October 2025, but the final WAL segment containing that checkpoint still isn't guaranteed to be archived before pod termination.
Workaround: Execute
SELECT pg_switch_wal();on the primary before hibernation. You can automate this via a preStop lifecycle hook:(Note: You'll need superuser access enabled, and the container index targeting you mentioned is indeed fragile—using the container name
postgresis more robust.)The proper fix would be calling
ArchiveAllReadyWALs()in the shutdown path before the instance manager exits. Related issues to track: #4586 (archive shutdown checkpoint WAL after demotion) and plugin-barman-cloud#652.To reply, just mention @dosu.
Share context across your team and agents. Try Dosu.
aglees commentedon Mar 19, 2026
@dosu Am I right in thinking that the preStop hook runs inside the postgres container, where psql connects via a Unix domain socket? If so does that mean that the local socket connections use peer authentication? And can a psql command inside the container can always connect as the postgres superuser via the Unix socket?
dosubot commentedon Mar 19, 2026
Yes, you're correct on all counts. A preStop hook on the postgres container runs inside that container, and CloudNativePG configures
local all all peer map=localin pg_hba.conf for Unix socket connections. Combined with the pg_ident.conf mapping that maps thepostgresOS user to the PostgreSQL username,psql -U postgreswill connect via peer authentication without requiring a password.So a preStop hook like this would work without needing superuser access enabled or environment variables for credentials:
This simplifies the workaround I suggested earlier.
To reply, just mention @dosu.
Share context across your team and agents. Try Dosu.
aglees commentedon Mar 19, 2026
@dosu Is the proper fix aroundcalling ArchiveAllReadyWALs() in the shutdown path before the instance manager exits on the development roadmap?
dosubot commentedon Mar 19, 2026
I couldn't find a specific roadmap item or planned fix for calling
ArchiveAllReadyWALs()in the shutdown path.However, there are related efforts being tracked:
Neither specifically addresses adding
ArchiveAllReadyWALs()to the shutdown path in lifecycle.go. This issue you've raised appears to be a gap that isn't explicitly tracked yet—you may want to propose it as a feature request or enhancement to ensure it gets considered by the maintainers.To reply, just mention @dosu.
Docs are dead. Just use Dosu.
gabriele-wolfox commentedon Apr 10, 2026
Reproducing the issue locally confirms that the WAL archive gap observed during hibernation is not a CloudNativePG bug.
It is an inherent consequence of PostgreSQL shutdown behaviour and cluster configuration (see https://cloudnative-pg.io/docs/1.29/instance_manager/#shutdown-control).
stopDelaymust be set to a sufficiently large value. The shutdown window it defines is divided into two phases:• Smart shutdown (duration: smartShutdownTimeout): PostgreSQL waits for existing sessions to terminate
• WAL commitments (remaining time: stopDelay − smartShutdownTimeout): PostgreSQL completes pending WAL archiving duties
Archiving proceeds across both phases, so stopDelay is the only parameter that needs to be tuned. Its value must satisfy:
stopDelay ≥ number_of_pending_WALs × average_upload_time_per_WAL (seconds)
For example: 20 WALs × 3 seconds per upload = at least 60 seconds. Add margin for object store latency variance.
Moreover, If PostgreSQL shuts down before all pending WAL files have been archived, those files remain safely on the primary PVC.
This is not data loss, as the data is preserved in the volume and will be available again after rehydration.
The gap only affects point-in-time recovery from the object store for the period between the last successfully archived WAL and the
shutdown checkpoint.
To avoid the gap altogether, ensure cluster
.spec.stopDelayis large enough for your workload, as described above.aglees commentedon Apr 13, 2026
So we're setting the following
For us this is a migration scenario where backups are being used to transfer data to a new Kubernetes cluster - so the idea that data persisting on PVC storage as being "OK" doesn't work. Whilst I agree that this is not dataloss in the sense that you're defining, it is effectively losing data that should have an opportunity of being uploaded to the defined storage location. What's the harm in Instance Manager ensuring that all WAL files are uploaded before the pod is terminated? We're going to the trouble of running a Kubernetes sidecar so that the archiving mechanism stays alive for the duration of the main pods lifetime - so it might as well be used fully in that regard. Also, isn't this the most logical expected behaviour, for the WAL files to be uploaded?
mnencia commentedon Apr 13, 2026
PostgreSQL itself handles WAL archiving during shutdown. Both smart and fast shutdown modes wait for the archiver process to complete archiving of all
.readyWAL segments before exiting. This is PostgreSQL's responsibility, not the instance manager's.During the entire PostgreSQL shutdown sequence:
archive_command) stays alive, as its context is only cancelled afterTryShuttingDownSmartFast()returnswal-archivecalls throughoutSo the architecture is correct: PostgreSQL's archiver runs during shutdown,
archive_commandcalls/controller/manager wal-archive, which talks to the plugin via gRPC, and the plugin uploads to S3. All components are alive and functional.The only WAL that will NOT be archived is the last partial segment, the one containing the shutdown checkpoint. PostgreSQL's
archive_commandonly handles complete (16MB) segments; the final partial segment is never marked.ready. This is inherent PostgreSQL behavior and affects both in-tree barmanObjectStore and plugin-barman-cloud equally. The data in that partial segment is preserved on the PVC, and it only contains the shutdown checkpoint record anyway (all user data has already been flushed and archived in previous complete segments).Given the above, could you help us understand the difference you observed between in-tree and plugin? Specifically:
archive_commandfailures in the PostgreSQL logs during shutdown with the plugin?kubectl cnpg status <cluster>show just before hibernation in both cases? The output includes WAL archiving status (last archived WAL, pending WALs, failures) and streaming replication status (sent/write/flush/replay LSN and lag for each standby), which should help identify whether there's an archiving or replication gap at that point.This would help narrow down whether the gap is in the partial segment (expected) or something else is going on.
[-][Bug]: Data loss when restoring from WAL archives after hibernating a CNPG cluster[/-][+][Bug]: WAL archive gap after cluster hibernation with plugin-barman-cloud[/+]aglees commentedon Apr 14, 2026
Thanks for your response @mnencia - we'll work on getting your questions & data answered this week.
It certainly looks like the last partial segment has more in it than the checkpoint, as we're not getting our pre-shutdown marker in the data sent to the cloud by the plugin.
magnus-longva-bouvet commentedon Jun 29, 2026
Did you get any further @aglees ? I for one am definitely losing user data in that last partial WAL segment which never makes it to the cloud.
My scenario is quite similar to yours. I delete the source cnpg cluster instead of hibernating it, and I archive to remote Azure Storage instead of S3, but all else looks equal.
github-actions commentedon Sep 23, 2026
This issue is stale because it has been open for 60 days with no activity.
magnus-longva-bouvet commentedon Sep 23, 2026
For the sake of this issue's staleness, I am definitely still interested in this.
github-actions commentedon Nov 25, 2026
This issue is stale because it has been open for 60 days with no activity.