> 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/concepts/cennso-postgresql-backup.md).

# Cennso PostgreSQL Backup

A Cennso PostgreSQL Backup is represented by the `PostgreSQLBackup` Custom Resource (CR) and defines a job to back up a PostgreSQL cluster managed by the [Cennso PostgreSQL Operator](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-postgresql-operator.md).

> [!IMPORTANT]
> The backup job runs against a read replica, never against the primary. The target `PostgreSQLInstance` must run `2` or more replicas. For more information, see the [PostgreSQL cluster size](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-postgresql-instance.md#postgresql-cluster-size) section of the Cennso PostgreSQL Instance document.

The sections below provide information about configuration parameters that you can specify in the `PostgreSQLBackup` CR. For more information on how to make a backup and restore from it, see the [Back up and restore Cennso PostgreSQL](https://docs.cennso.com/cennso/cennso-db/latest/operation-guides/cennso-postgresql-backup.md) document.

## Configuration restrictions

The values configured in the `PostgreSQLBackup` Custom Resource have the following restrictions:

- The PostgreSQL cluster must run at least one read replica.
- The `PostgreSQLBackup` **metadata.name** must match the **metadata.name** of the `PostgreSQLInstance` you want to back up, and must not exceed `38` characters.
- The `PostgreSQLBackup` **spec.namespace** must match the Kubernetes namespace where the database instance is deployed.
- The `PostgreSQLBackup` **spec.resticRepository** must start with one of the repository types supported by Restic: `azure`, `b2`, `gs`, `local`, `rclone`, `rest`, `s3`, `sftp`, or `swift`.
- The `PostgreSQLBackup` **spec.additionalResticOpts.cacheDir** must not contain single quote (`'`) characters.
- The following parameters are split on whitespace, so a single argument value cannot contain spaces:
  - **spec.additionalResticOpts.initExtraArgs**
  - **spec.additionalResticOpts.pruneExtraArgs**
  - **spec.additionalResticOpts.backupExtraArgs**
  - **spec.pgBasebackupExtraArgs**
- If **spec.additionalResticOpts.pruneRepository** is `true`, **spec.additionalResticOpts.pruneExtraArgs** must specify a retention policy. For more information, see the [Restic settings](#restic-settings) section.

## Kubernetes cluster secret reference

To deploy the Cennso PostgreSQL Backup to a Core Cluster, you must specify a reference to the [Kubernetes secret](https://kubernetes.io/docs/concepts/configuration/secret/) so the cluster is accessible. You can do this using the following configuration parameters:

```yaml
spec:
  connectionSecretRef:
    name: {CORE-CLUSTER-NAME}
    namespace: {CORE-CLUSTER-SECRET-NAMESPACE}
    key: kubeconfig
```

Set **spec.connectionSecretRef.name** to the name of the Core Cluster where the Cennso PostgreSQL Backup should be installed. The **spec.connectionSecretRef.namespace** configuration parameter defines the Kubernetes Namespace on the Management Cluster where the Kubernetes secret to access this Core Cluster is stored. The **spec.connectionSecretRef.key** is an optional configuration parameter that defines the key in the Kubernetes secret which contains the kubeconfig for the Core Cluster. Its value defaults to `kubeconfig`.

If you want to deploy the Cennso PostgreSQL Backup to the Management Cluster, do not specify **spec.connectionSecretRef**. In both cases, the target cluster must be the same as the one of the Cennso PostgreSQL Operator that manages the namespace of the database instances.

## Backup jobs placement

The backup jobs specified by the Cennso PostgreSQL Backup CR are deployed in the Kubernetes namespace specified by the following configuration option:

```yaml
spec:
  namespace: {POSTGRESQL-CLUSTER-NAMESPACE}
```

## Backup jobs scheduling and execution

To configure when backup jobs should be performed, you can use the following configuration option:

```yaml
spec:
  schedule: {BACKUP-SCHEDULE}
```

The `{BACKUP-SCHEDULE}` must be a cron expression which specifies how often backup jobs are performed. The schedule is evaluated in the `UTC` time zone. For example:

- `spec.schedule: "0 6 * * 1"` - run a backup job weekly on Monday at 6 AM
- `spec.schedule: "@daily"` - run a backup job once a day at midnight
- `spec.schedule: "0 */3 * * *"` - run a backup job every three hours

For more information, see the [Writing a CronJob spec](https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/#writing-a-cronjob-spec) documentation.

You can also control how long a backup run may take, how many times failures are retried, and how many completed jobs are kept. These options are optional and have the following default values:

```yaml
spec:
  activeDeadlineSeconds: 7200
  backoffLimit: 2
  successfulJobsHistoryLimit: 1
  failedJobsHistoryLimit: 3
```

- The **spec.activeDeadlineSeconds** parameter sets the maximum time a single backup run may take before Kubernetes terminates it and marks the run as failed. Because only one backup run is allowed at a time, this prevents a hung run from blocking all following scheduled backups. It is highly recommended to increase this value for large databases whose backups can take longer.
- The **spec.backoffLimit** parameter sets how many times a failed backup run is retried before it is marked as failed.
- The **spec.successfulJobsHistoryLimit** and **spec.failedJobsHistoryLimit** parameters set how many completed successful and failed backup jobs Kubernetes retains. Failed jobs are kept so that their logs can be inspected when a backup fails.

## Backup source

The backup job looks for a ready read replica pod of the PostgreSQL cluster in **spec.namespace** and connects to it as the replication user of the database operator. Before it takes the backup, the job checks that the pod is a replica, that it streams [WAL](https://www.postgresql.org/docs/current/wal-intro.html) from the primary, and that it is not lagging too far behind. You can configure the allowed replication lag using the following configuration option:

```yaml
spec:
  maxReplicationLagBytes: 16777216
```

The **spec.maxReplicationLagBytes** parameter sets the maximum amount of WAL, in bytes, that the replica may have received but not yet replayed when the backup starts. A replica that lagged further behind is not backed up, and the job fails. The default value is `16777216` bytes, which is `16` MiB.

The replication user authenticates with a client certificate. The backup job reads the certificate from a Kubernetes Secret in **spec.namespace**, which you can configure using the following configuration option:

```yaml
spec:
  replicationSecretName: {REPLICATION-SECRET-NAME}
```

By default, the backup job uses the `{POSTGRESQL-INSTANCE-NAME}-replication-cert` Secret created by the database operator. If the target `PostgreSQLInstance` uses your own replication certificate specified by **spec.replicationTLSSecretName**, set this field to the certificate's secret name.

## Backup storage

The backup job writes a local copy of the database before it uploads the copy to the Restic repository. To hold the local copy on a dedicated volume, use the following configuration options:

```yaml
spec:
  storage:
    capacity: 20Gi
    className: {STORAGE-CLASS-NAME}
```

The backup job requests an ephemeral `ReadWriteOnce` volume of **spec.storage.capacity** in the `StorageClass` **spec.storage.className**. The volume is deleted together with the job pod. The capacity must fit a full copy of the database together with the WAL streamed during the backup.

If **spec.storage** is omitted, the local copy is written to the ephemeral storage of the node that runs the job pod. In this case, the node must have room for a full copy of the database.

## Restic settings

The backup container uses [Restic](https://restic.net/) to upload the `pg_basebackup` output to a repository. To configure a [Restic repository](https://restic.readthedocs.io/en/latest/030_preparing_a_new_repo.html), you can use the following configuration option:

```yaml
spec:
  resticRepository: s3:http://minio:9000/postgresql-backup
```

The value of this parameter must be a valid URI supported by the `restic init` command. The snapshots are stored with the `PostgreSQLInstance` name as the Restic host name, so that several PostgreSQL clusters can share one repository.

In addition, you can pass extra configuration options for the Restic repository initialization and the backup procedure using the following configuration options:

```yaml
spec:
  additionalResticOpts:
    initExtraArgs: "--insecure-tls"
    backupExtraArgs: "--insecure-tls"
```

The list of supported options you can find in the official documentation for the [init](https://restic.readthedocs.io/en/latest/030_preparing_a_new_repo.html) and [backup](https://restic.readthedocs.io/en/latest/040_backup.html) commands.

To save disk space and apply a retention policy, you can remove old backups using the following configuration options:

```yaml
spec:
  additionalResticOpts:
    pruneRepository: true
    pruneExtraArgs: "--prune --keep-last 7"
```

If you set the **spec.additionalResticOpts.pruneRepository** to `true` and do not specify `--prune` in **spec.additionalResticOpts.pruneExtraArgs**, only metadata of the affected snapshots is removed. Include `--prune` in **spec.additionalResticOpts.pruneExtraArgs** if you also want Restic to remove unreferenced data.

If you set **spec.additionalResticOpts.pruneRepository** to `true`, you must also specify a retention policy in **spec.additionalResticOpts.pruneExtraArgs** (for example, `--keep-last 7`). The backup job runs the `restic forget` command with these arguments, and the command cannot run without a policy. If you leave **spec.additionalResticOpts.pruneExtraArgs** empty, the Kubernetes API server rejects the `PostgreSQLBackup` with the following error:

```
additionalResticOpts.pruneExtraArgs must specify a retention policy (for example, --keep-daily 7) when pruneRepository is true
```

For more information on pruning restic repositories, see the [official documentation](https://restic.readthedocs.io/en/stable/060_forget.html).

To specify the directory where Restic stores its local cache during backup operations, use **spec.additionalResticOpts.cacheDir**:

```yaml
spec:
  additionalResticOpts:
    cacheDir: "/tmp/restic-cache"
```

## Backend storage credentials

Using the Restic utility, the backups are stored in one of the supported backends. These backends often need authorisation and authentication. You can use the following configuration options to refer to a Kubernetes Secret that stores settings for authorisation and authentication:

```yaml
spec:
  credentialsSecretRef:
    name: "{SECRET-NAME}"
```

For more information, see the [Back up and restore Cennso PostgreSQL](https://docs.cennso.com/cennso/cennso-db/latest/operation-guides/cennso-postgresql-backup.md) document.

## Additional options for pg_basebackup

The backup job runs `pg_basebackup` in the plain format with the WAL streamed into the backup, so that the backup is consistent and no continuous WAL archiving is required between the backup runs. After the copy is taken, the job checks it with [`pg_verifybackup`](https://www.postgresql.org/docs/current/app-pgverifybackup.html) before the upload.

You can use **spec.pgBasebackupExtraArgs** to specify additional configuration options of `pg_basebackup`, which are passed to this utility when performing a backup:

```yaml
spec:
  pgBasebackupExtraArgs: "--max-rate=50M --checkpoint=spread"
```

You can find the list of available configuration options in the [official documentation](https://www.postgresql.org/docs/current/app-pgbasebackup.html).

## Backup job resources

You can specify [resources](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) for the backup job using the following configuration options:

```yaml
spec:
  resources:
    requests:
      cpu: 500m
      memory: 512Mi
    limits:
      cpu: 2
      memory: 2Gi
```

## Image and pull secret

You can configure the image of the backup job and the Kubernetes Secret used to pull it with the following configuration options:

```yaml
spec:
  image:
    registry: registry.cennso.com/cennso/pg-basebackup-restic
    tag: v18.3-2-cennso-0.2
  imagePullSecretRef:
    name: cennso-pull-secret
```
