> For the complete documentation index, see [llms.txt](https://docs.cennso.com/cennso/cennso-db/latest/llms.txt) (all documentation: [llms.txt](https://docs.cennso.com/llms.txt)). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cennso.com/cennso/cennso-db/latest/operation-guides/cennso-postgresql-backup.md).

# Back up and restore

This guide describes how to use the `PostgreSQLBackup` Custom Resource to:

- [Perform a backup of a database](#perform-a-backup-of-a-database)
- [Restore a database from a backup](#restore-a-database-from-a-backup)

## Perform a backup of a database

This section describes how you can prepare backups of your database deployed using the [Cennso PostgreSQL Instance](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-postgresql-instance.md).

> [!IMPORTANT]
> The backup job runs against a read replica instead of the primary, so the target `PostgreSQLInstance` must run at least one read replica, with **spec.instances[].replicas** set to `2` or more in at least one instance set. If the cluster runs only a single instance, the backup job cannot find a pod to back up and fails with the error: `ERROR: No ready read replica found. Backup can be performed only on a read replica.`. The job also refuses a replica that does not stream WAL from the primary or lags behind it by more than **spec.maxReplicationLagBytes**. For more information, see the [Configuration restrictions](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-postgresql-backup.md#configuration-restrictions) and [Backup source](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-postgresql-backup.md#backup-source) sections.

To deploy a Cennso PostgreSQL Backup, execute the following steps:

1. Prepare the Kubernetes secret in the Kubernetes namespace where your PostgreSQL cluster is up and running. This secret should contain the list of environment variables with the data needed for the authorisation at a [Restic](https://restic.net/) backend. To prepare a secret, create a file, for example `secret.data`, with the list of environment variables which you need to authorise at a restic backend. For example:

   ```bash
   export AWS_ACCESS_KEY_ID={MY_ACCESS_KEY}
   export AWS_SECRET_ACCESS_KEY={MY_SECRET_ACCESS_KEY}
   export RESTIC_PASSWORD={RESTIC_PASSWORD}
   ```

   > [!NOTE]
   > To find information about all supported environment variables, see the [official documentation](https://restic.readthedocs.io/en/stable/030_preparing_a_new_repo.html).

   The backup job loads this file in a shell before it runs Restic, so each line must start with `export`. The job reads the file from the `secret` key of the Kubernetes secret, so the key must have exactly this name.

   At the next step, encode the contents of the file to base64:

   ```bash
   cat secret.data | base64 -w0
   ```

   Create a Kubernetes secret file (for example `secret.yaml`) and put the output of the previous command to the **data.secret** field. For example:

   ```yaml
   apiVersion: v1
   kind: Secret
   metadata:
     name: {SECRET-NAME}
     namespace: {NAMESPACE-WITH-POSTGRESQL-CLUSTER}
   type: Opaque
   data:
     secret: ZXhwb3J0IEFXU19BQ0NFU1NfS0VZX0lEPXtNWV9BQ0NFU1NfS0VZfQpleHBvcnQgQVdTX1NFQ1JFVF9BQ0NFU1NfS0VZPXtNWV9TRUNSRVRfQUNDRVNTX0tFWX0KZXhwb3J0IFJFU1RJQ19QQVNTV09SRD17UkVTVElDX1BBU1NXT1JEfQo=
   ```

   Apply this secret to the target cluster where you want to perform backups using the following command:

   ```bash
   kubectl apply -f secret.yaml -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER}
   ```

2. Prepare the `postgresql-backup-cr.yaml` file with the `PostgreSQLBackup` Custom Resource (CR) to deploy the Cennso PostgreSQL Backup in your Management Cluster. For example:

   ```yaml
   apiVersion: db.contrib.cennso.com/v1alpha1
   kind: PostgreSQLBackup
   metadata:
     name: {POSTGRESQL-INSTANCE-NAME}
     namespace: cennso-infra
   spec:
     connectionSecretRef:
       name: {CORE-CLUSTER-NAME}
       namespace: cennso-infra
     namespace: {NAMESPACE-WITH-POSTGRESQL-CLUSTER}
     schedule: "0 0 * * *"
     activeDeadlineSeconds: 7200
     backoffLimit: 2
     successfulJobsHistoryLimit: 1
     failedJobsHistoryLimit: 3
     resticRepository: "s3:http://minio:9000/postgresql-backup"
     credentialsSecretRef:
       name: {SECRET-NAME}
     maxReplicationLagBytes: 16777216
     storage:
       capacity: 20Gi
       className: {STORAGE-CLASS-NAME}
     additionalResticOpts:
       initExtraArgs: ""
       backupExtraArgs: ""
       pruneRepository: false
       pruneExtraArgs: ""
     pgBasebackupExtraArgs: ""
   ```

   The **metadata.name** must match the **metadata.name** of the `PostgreSQLInstance` you want to back up, and **spec.namespace** must match the namespace where this instance runs. Omit **spec.connectionSecretRef** to run the backup on the Management Cluster.

   > [!IMPORTANT]
   > The `PostgreSQLBackup` resource has restrictions on some configurable values. For more information, see the [Configuration restrictions](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-postgresql-backup.md#configuration-restrictions) section.

3. Apply the prepared CR to your Management Cluster:

   ```bash
   kubectl apply -f postgresql-backup-cr.yaml
   ```

4. Check your target cluster for the created Kubernetes CronJob to check if backups are configured to run at the specified time:

   ```bash
   kubectl get cronjobs -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER}
   ```

The example above shows the Custom Resource that creates a Kubernetes CronJob. This CronJob performs a backup of the PostgreSQL cluster named `{POSTGRESQL-INSTANCE-NAME}`, deployed in the Core Cluster specified by the `{CORE-CLUSTER-NAME}` and located in the namespace specified by the `{NAMESPACE-WITH-POSTGRESQL-CLUSTER}`. It performs a backup each day at 00:00 UTC from one of the read replicas of the cluster using `pg_basebackup` and uploads it to the Restic repository. The `{SECRET-NAME}` must specify the name of the Kubernetes secret which you created in the previous step.

For more information about available configuration options, see the [Cennso PostgreSQL Backup](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-postgresql-backup.md) document.

## Restore a database from a backup

If your database or the data was corrupted in a way that you can not continue to run PostgreSQL instances on existing data files, you have to restore the database from a backup.

The steps below restore the backup to the data volumes of an existing PostgreSQL cluster. If the PostgreSQL cluster no longer exists, deploy a new one first using the instructions given in the [Deploy Cennso PostgreSQL](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-postgresql.md) document. The new cluster must have the same name and the same number of instances as the one you backed up.

Before restoring the database from a backup, make sure you know the names of the PostgreSQL instances and their roles. To get the PostgreSQL Pod names and their roles, use the following command:

```bash
kubectl get pods -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} -l postgres-operator.crunchydata.com/instance \
  -o custom-columns='POD:.metadata.name,ROLE:.metadata.labels.postgres-operator\.crunchydata\.com/role'
```

The output should look like this:

```
POD                                    ROLE
postgresql-instance-instance1-2bl2-0   primary
postgresql-instance-instance1-rdjp-0   replica
```

Now you can proceed to restore your database from the backup:

1. Pause the `PostgreSQLInstance` related to your PostgreSQL cluster on the Management Cluster. While it is paused, Crossplane does not reconcile the resource, so the changes you make to the cluster in the next steps are not reverted. First, find the name of the `PostgreSQLInstance`:

   ```bash
   kubectl get postgresqlinstance -n cennso-infra
   ```

   The output should look like this:

   ```
   NAME                  SYNCED   READY   COMPOSITION                   AGE
   postgresql-instance   True     True    percona-postgresql-instance   11m
   ```

   Then pause the `PostgreSQLInstance` with the following command:

   ```bash
   kubectl -n cennso-infra annotate postgresqlinstance {POSTGRESQL-INSTANCE} crossplane.io/paused=true
   ```

2. Pause the Crossplane `Object` that manages the `PerconaPGCluster` of your PostgreSQL cluster. The `PostgreSQLInstance` composes several `Object` resources, and the one with the `PerconaPGCluster` kind keeps the `PerconaPGCluster` on the target cluster in sync with the composition. While it is paused, the provider does not revert the changes you make to the `PerconaPGCluster`. To find its name, list the `Object` resources composed by your `PostgreSQLInstance`:

   ```bash
   kubectl -n cennso-infra get objects.kubernetes.m.crossplane.io -l crossplane.io/composite={POSTGRESQL-INSTANCE}
   ```

   The output should look like this. Take the name of the `Object` with the `PerconaPGCluster` kind:

   ```
   NAME                               KIND               PROVIDERCONFIG                            SYNCED   READY   AGE
   postgresql-instance-42ba43805c7b   Namespace          postgresql-instance-instance-kubernetes   True     True    11m
   postgresql-instance-ab83f2bed692   PerconaPGCluster   postgresql-instance-instance-kubernetes   True     True    11m
   ```

   Then pause this `Object` with the following command:

   ```bash
   kubectl -n cennso-infra annotate objects.kubernetes.m.crossplane.io {OBJECT-WITH-PERCONAPGCLUSTER} crossplane.io/paused=true
   ```

3. Stop the PostgreSQL cluster on the target cluster. The `PerconaPGCluster` has the same name as your `PostgreSQLInstance` and runs in the namespace of the PostgreSQL cluster. Set **spec.pause** to `true`, so the Cennso PostgreSQL Operator shuts down the PostgreSQL instances and [PgBouncer](https://www.pgbouncer.org/) and removes their Pods. The persistent volumes with the data files are kept, so you can overwrite the data files in the next steps:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} patch perconapgcluster {POSTGRESQL-INSTANCE} --type merge -p '{"spec":{"pause":true}}'
   ```

   Wait until the operator reports the cluster as `paused` and no PostgreSQL Pods are left:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} get perconapgcluster {POSTGRESQL-INSTANCE}
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} get pods -l postgres-operator.crunchydata.com/instance
   ```

   The output should look like this:

   ```
   NAME                  ENDPOINT                                                   STATUS   POSTGRES   PGBOUNCER   AGE
   postgresql-instance   postgresql-instance-pgbouncer.cennso-postgresql-test.svc   paused   0          0           25m
   No resources found in cennso-postgresql-test namespace.
   ```

   The PersistentVolumeClaims of the instances must still be present. Note their names, as you need them for the next step:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} get pvc -l postgres-operator.crunchydata.com/instance
   ```

   The output should look like this:

   ```
   NAME                                        STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS       VOLUMEATTRIBUTESCLASS   AGE
   postgresql-instance-instance1-2bl2-pgdata   Bound    pvc-af438020-97e7-4b18-aa04-a5ea77cb7498   20Gi       RWO            openebs-hostpath   <unset>                 11m
   postgresql-instance-instance1-rdjp-pgdata   Bound    pvc-c911b708-7e88-4dde-9682-6a443b481723   20Gi       RWO            openebs-hostpath   <unset>                 11m
   ```

4. Deploy a restore Pod for every PostgreSQL instance of the cluster, one for the primary and one for each read replica. Each Pod mounts the PersistentVolumeClaim of one instance, so you can write the restored data files to it. You must restore the same backup to all instances. If you restore only the primary, the read replicas keep data files from a newer timeline and cannot follow the restored primary.

   Create a file, for example `restore-primary.yaml`, with the following content:

   ```yaml
   apiVersion: v1
   kind: Pod
   metadata:
     name: pg-restore-primary
     namespace: {NAMESPACE-WITH-POSTGRESQL-CLUSTER}
   spec:
     restartPolicy: Never
     securityContext:
       runAsUser: 26
       runAsGroup: 26
       fsGroup: 26
     imagePullSecrets:
       - name: cennso-pull-secret
     containers:
       - name: restore
         image: registry.cennso.com/cennso/pg-basebackup-restic:v18.3-2-cennso-0.2
         command: ["sleep", "infinity"]
         volumeMounts:
           - name: pgdata
             mountPath: /pgdata
           - name: restic
             mountPath: /etc/restic/credentials
     volumes:
       - name: pgdata
         persistentVolumeClaim:
           claimName: {PRIMARY-PVC-NAME}
       - name: restic
         secret:
           secretName: {SECRET-NAME}
   ```

   Replace `{PRIMARY-PVC-NAME}` with the PersistentVolumeClaim of the primary instance from the previous step. The claim name is the Pod name of the instance followed by `-pgdata`, for example `postgresql-instance-instance1-2bl2-pgdata`. Use the image of the `PostgreSQLBackup` if you changed **spec.image** there.

   Create a second file, for example `restore-replica.yaml`, with the same content, but set **metadata.name** to `pg-restore-replica` and **spec.volumes[].persistentVolumeClaim.claimName** to the PersistentVolumeClaim of the read replica. If the cluster runs more than one read replica, create one file per replica.

   Apply the files to the target cluster and wait until the Pods are running:

   ```bash
   kubectl apply -f restore-primary.yaml -f restore-replica.yaml
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} get pods pg-restore-primary pg-restore-replica
   ```

   The output should look like this:

   ```
   NAME                 READY   STATUS    RESTARTS   AGE
   pg-restore-primary   1/1     Running   0          7m39s
   pg-restore-replica   1/1     Running   0          7m35s
   ```

5. Restore the backup to the data volume of the primary. Open a shell in the restore Pod of the primary:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} exec -it pg-restore-primary -- bash
   ```

   Run all commands of this step inside this shell. First, load the Restic credentials from the mounted secret and set the repository. Use the same value as **spec.resticRepository** of your `PostgreSQLBackup`:

   ```bash
   source /etc/restic/credentials/secret
   export RESTIC_REPOSITORY={RESTIC-REPOSITORY}
   ```

   List the snapshots of your PostgreSQL cluster and choose the one you want to restore. The backup job stores the snapshots with the name of the `PostgreSQLInstance` as the Restic host name. If **spec.additionalResticOpts.backupExtraArgs** of your `PostgreSQLBackup` contains `--insecure-tls`, add it to every `restic` command in this step as well:

   ```bash
   restic snapshots --host {POSTGRESQL-INSTANCE}
   ```

   Move the current data directory and WAL directory of the instance aside. The directory names contain the PostgreSQL major version, for example `pg18` and `pg18_wal` for PostgreSQL `18`:

   ```bash
   mv /pgdata/pg18 /pgdata/pg18.old
   mv /pgdata/pg18_wal /pgdata/pg18_wal.old
   ```

   Restore the chosen snapshot to a temporary directory on the data volume. The snapshot contains the `pg_basebackup` output under the `/backup/pgdata` path:

   ```bash
   restic restore {SNAPSHOT-ID} --target /pgdata/restore
   ```

   Move the restored data directory to the place of the data directory and restrict its permissions, as PostgreSQL refuses to start with a data directory that other users can access. The restored data directory contains the WAL streamed during the backup in its `pg_wal` subdirectory. You do not need to create the WAL directory yourself, as the instance moves `pg_wal` to its WAL directory on startup and replaces it with a symbolic link:

   ```bash
   mv /pgdata/restore/backup/pgdata /pgdata/pg18
   chmod 700 /pgdata/pg18
   ```

   Check that the restored data directory is a valid PostgreSQL cluster and note its system identifier. It must be the same on all instances after the restore:

   ```bash
   pg_controldata /pgdata/pg18 | grep 'system identifier'
   ```

   The output should look like this:

   ```
   Database system identifier:           7693527883571142716
   ```

   Leave the shell with `exit`.

6. Repeat the previous step in the restore Pod of every read replica, for example in `pg-restore-replica`. Restore the same snapshot there. After the restore, the system identifier reported by `pg_controldata` must match the one of the primary.

7. Update the cluster state of [Patroni](https://docs.cennso.com/cennso/cennso-db/latest/troubleshooting/patroni.md), the high availability manager that runs inside every PostgreSQL instance. Patroni stores this state in annotations of two Kubernetes `Endpoints` resources in the namespace of the PostgreSQL cluster:

   - `{POSTGRESQL-INSTANCE}-ha-config` holds the `initialize` annotation with the system identifier of the cluster. If it differs from the system identifier of the restored data directory, Patroni refuses to start the instances, as they appear to belong to a different cluster.
   - `{POSTGRESQL-INSTANCE}-ha` holds the `optime` annotation with the last WAL position of the former primary. The restored data is behind this position, so Patroni treats all instances as lagging and does not select a new primary.

   Set the `initialize` annotation to the system identifier you noted in step 5 and remove the `optime` annotation:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} annotate --overwrite endpoints {POSTGRESQL-INSTANCE}-ha-config initialize={SYSTEM-IDENTIFIER}
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} annotate endpoints {POSTGRESQL-INSTANCE}-ha optime-
   ```

   Check that the `initialize` annotation now holds the new system identifier:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} get endpoints {POSTGRESQL-INSTANCE}-ha-config -o jsonpath='{.metadata.annotations.initialize}{"\n"}'
   ```

   The output should look like this:

   ```
   7693527883571142716
   ```

8. Start the PostgreSQL cluster again. Set **spec.pause** of the `PerconaPGCluster` back to `false`. The Cennso PostgreSQL Operator starts the PostgreSQL instances and PgBouncer again. Each instance finds the restored data directory on its volume and Patroni elects one of the instances as the new primary:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} patch perconapgcluster {POSTGRESQL-INSTANCE} --type merge -p '{"spec":{"pause":false}}'
   ```

   Wait until the operator reports the cluster as `ready` and all PostgreSQL Pods are running, with one of them as the primary and the others as replicas:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} get perconapgcluster {POSTGRESQL-INSTANCE}
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} get pods -l postgres-operator.crunchydata.com/instance -o custom-columns='POD:.metadata.name,ROLE:.metadata.labels.postgres-operator\.crunchydata\.com/role'
   ```

   The output should look like this:

   ```
   NAME                  ENDPOINT                                                   STATUS   POSTGRES   PGBOUNCER   AGE
   postgresql-instance   postgresql-instance-pgbouncer.cennso-postgresql-test.svc   ready    2          2           37m
   POD                                    ROLE
   postgresql-instance-instance1-2bl2-0   primary
   postgresql-instance-instance1-rdjp-0   replica
   ```

   Finally, resume the Crossplane resources you paused in steps 1 and 2 on the Management Cluster, so that Crossplane manages the PostgreSQL cluster again. Remove the `crossplane.io/paused` annotation from the `Object` with the `PerconaPGCluster` kind and from the `PostgreSQLInstance`:

   ```bash
   kubectl -n cennso-infra annotate objects.kubernetes.m.crossplane.io {OBJECT-WITH-PERCONAPGCLUSTER} crossplane.io/paused-
   kubectl -n cennso-infra annotate postgresqlinstance {POSTGRESQL-INSTANCE} crossplane.io/paused-
   ```

   Check that the `PostgreSQLInstance` is synced and ready again:

   ```bash
   kubectl -n cennso-infra get postgresqlinstance {POSTGRESQL-INSTANCE}
   ```

   The output should look like this:

   ```
   NAME                  SYNCED   READY   COMPOSITION                   AGE
   postgresql-instance   True     True    percona-postgresql-instance   37m
   ```

   Verify that the restored data is in place before you continue with the next step.

9. Remove the old data from the data volumes. The data directory and WAL directory you moved aside in step 5 are still on the volume of every instance as `pg18.old` and `pg18_wal.old`, together with the empty `restore` directory left by Restic. They take up as much disk space as the restored data, so remove them after you verify the restored data. Run the following commands in the restore Pod for the primary and in the restore Pod for each replica:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} exec pg-restore-primary -- rm -rf /pgdata/pg18.old /pgdata/pg18_wal.old /pgdata/restore
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} exec pg-restore-replica -- rm -rf /pgdata/pg18.old /pgdata/pg18_wal.old /pgdata/restore
   ```

   Then delete the restore Pods, as they are no longer needed:

   ```bash
   kubectl -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} delete pod pg-restore-primary pg-restore-replica
   ```

From now on, your PostgreSQL cluster runs with the data restored from the backup. For more information on how to validate your PostgreSQL cluster, see the [Validate the PostgreSQL cluster](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-postgresql-validation.md) document.
