Skip to content

[Bug]: WAL archive gap after cluster hibernation with plugin-barman-cloud #10341

Description

@aglees

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

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

  1. Create a CNPG cluster with plugin-barman-cloud configured for WAL archiving to S3, let it run for a while, WAL archiving is working correctly
  2. Backup the database to S3
  3. Insert data into the database (for timestamping purposes)
  4. Hibernate the cluster
  5. Create a new cluster restoring from the WAL archive of the hibernated one
  6. 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

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

  2. preStop hooks: We've seen recommendations to look at adding a hook to run pg_switch_wal via cnpg.io/podPatch annotation. This feels a bit fragile as dependent on index of containers to attach this to the correct container.

  3. 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. After TryShuttingDownSmartFast() returns in lifecycle.go:148, the instance manager exits without sweeping remaining .ready WAL 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: 3600

Relevant log output

Code of Conduct

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

Activity

  1. added
    triage
    on Mar 19, 2026
  2. dosubot commented on Mar 19, 2026

    @dosubot

    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. After TryShuttingDownSmartFast() returns, the instance manager exits without sweeping remaining .ready WAL 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:

    metadata:
      annotations:
        cnpg.io/podEnvFrom: '{"name": "PGPASSWORD", "valueFrom": {"secretKeyRef": {"name": "postgresql-superuser", "key": "password"}}}'
        cnpg.io/podPatch: |
          spec:
            containers:
            - name: postgres
              lifecycle:
                preStop:
                  exec:
                    command:
                    - /bin/sh
                    - -c
                    - psql -U postgres -c "SELECT pg_switch_wal();"

    (Note: You'll need superuser access enabled, and the container index targeting you mentioned is indeed fragile—using the container name postgres is 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.

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

  3. aglees commented on Mar 19, 2026

    @aglees
    Author

    @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?

  4. dosubot commented on Mar 19, 2026

    @dosubot

    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=local in pg_hba.conf for Unix socket connections. Combined with the pg_ident.conf mapping that maps the postgres OS user to the PostgreSQL username, psql -U postgres will 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:

    lifecycle:
      preStop:
        exec:
          command:
          - /bin/sh
          - -c
          - psql -U postgres -c "SELECT pg_switch_wal();"

    This simplifies the workaround I suggested earlier.

    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

  5. aglees commented on Mar 19, 2026

    @aglees
    Author

    @dosu Is the proper fix aroundcalling ArchiveAllReadyWALs() in the shutdown path before the instance manager exits on the development roadmap?

  6. dosubot commented on Mar 19, 2026

    @dosubot

    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:

    • plugin-barman-cloud#652 discusses the broader issue of unrestorable backups on low-activity databases and proposes fixes at either the Barman tool level or plugin level (triggering WAL switch after backups)
    • #4586 addresses archiving the shutdown checkpoint WAL after demotion (deferred to 1.24+)

    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.

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

  7. gabriele-wolfox commented on Apr 10, 2026

    @gabriele-wolfox
    Contributor

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

    stopDelay must 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.stopDelay is large enough for your workload, as described above.

  8. aglees commented on Apr 13, 2026

    @aglees
    Author

    So we're setting the following

    spec:
      smartShutdownTimeout: 180
      startDelay: 3600
      stopDelay: 1800

    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?

  9. mnencia commented on Apr 13, 2026

    @mnencia
    Member

    PostgreSQL itself handles WAL archiving during shutdown. Both smart and fast shutdown modes wait for the archiver process to complete archiving of all .ready WAL segments before exiting. This is PostgreSQL's responsibility, not the instance manager's.

    During the entire PostgreSQL shutdown sequence:

    • The instance manager's local HTTP cache server (needed by archive_command) stays alive, as its context is only cancelled after TryShuttingDownSmartFast() returns
    • The plugin sidecar (native sidecar) stays alive, since the kubelet only sends SIGTERM to sidecar initContainers after the main container has fully exited
    • The plugin's gRPC server is available for wal-archive calls throughout

    So the architecture is correct: PostgreSQL's archiver runs during shutdown, archive_command calls /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_command only 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:

    • Were both tests performed with the same timing between data insertion and hibernation?
    • Were there any archive_command failures in the PostgreSQL logs during shutdown with the plugin?
    • What does 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.

  10. changed the title [-][Bug]: Data loss when restoring from WAL archives after hibernating a CNPG cluster[/-] [+][Bug]: WAL archive gap after cluster hibernation with plugin-barman-cloud[/+] on Apr 13, 2026
  11. aglees commented on Apr 14, 2026

    @aglees
    Author

    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.

  12. added
    bug 🐛
    and removed on Jun 21, 2026
  13. magnus-longva-bouvet commented on Jun 29, 2026

    @magnus-longva-bouvet

    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.

  14. github-actions commented on Sep 23, 2026

    @github-actions
    Contributor

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

  15. magnus-longva-bouvet commented on Sep 23, 2026

    @magnus-longva-bouvet

    For the sake of this issue's staleness, I am definitely still interested in this.

  16. github-actions commented on Nov 25, 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