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

# Cennso PostgreSQL Instance

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

> [!IMPORTANT]
> Before deploying the PostgreSQL cluster, you must have the Cennso PostgreSQL Operator up and running, and the namespace of the PostgreSQL cluster must be listed in its **spec.watchNamespaces**.

The sections below provide information about configuration parameters that you can specify in the `PostgreSQLInstance` CR. For more information on how to configure and deploy the database cluster, see the [Deploy Cennso PostgreSQL](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-postgresql.md) and [Cennso PostgreSQL Instance Custom Resource Definition](https://docs.cennso.com/cennso/cennso-db/latest/technical-reference/configurations/cennso-postgresql/xpostgresqlinstance_definition.md) documents.

## Naming constraint

> [!IMPORTANT]
> The `PostgreSQLInstance` **metadata.name** must not exceed `38` characters.

A `PostgreSQLBackup` must carry the same **metadata.name** as its `PostgreSQLInstance`, and the backup CronJob name derived from it must fit the Kubernetes limit of `52` characters for a CronJob name. The API server rejects a longer name.

## Kubernetes cluster secret reference

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

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

Set **spec.connectionSecretRef.name** to the name of the Core Cluster where the Cennso PostgreSQL Instance 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.

If you want to deploy the Cennso PostgreSQL Instance 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.

## Image configuration

You can use the following configuration parameters to specify the versions of the container images along with the secret to pull the images of the Cennso PostgreSQL Instance:

```yaml
spec:
  image:
    registry: {DATABASE-INSTANCE-IMAGE-REPOSITORY}
    tag: {DATABASE-INSTANCE-IMAGE-TAG}
  initContainer:
    image: {DATABASE-INSTANCE-INIT-IMAGE}
  imagePullSecretRef:
    name: {SECRET-NAME}
```

## Scheduling and placement configuration

The PostgreSQL instances specified by the Cennso PostgreSQL Instance CR are deployed in the Kubernetes namespace specified by the following configuration option:

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

The PostgreSQL instances are organised in instance sets, configured by the required **spec.instances** configuration option. Each entry defines a named set of PostgreSQL Pods with its own number of replicas, resources, and storage. To control where the Pods of an instance set run, use the standard Kubernetes scheduling fields:

- [**spec.instances[].affinity**](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#affinity-and-anti-affinity)
- [**spec.instances[].tolerations**](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/)
- [**spec.instances[].topologySpreadConstraints**](https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/)
- [**spec.instances[].priorityClassName**](https://kubernetes.io/docs/concepts/scheduling-eviction/pod-priority-preemption/)

> [!NOTE]
> If you set **spec.instances[].priorityClassName**, the PriorityClass must exist on the target cluster.

For example, the following configuration places an instance set on two nodes, one replica per node:

```yaml
spec:
  instances:
    - name: instance1
      replicas: 2
      storage:
        capacity: 20Gi
        className: {STORAGE-CLASS-NAME}
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
              - matchExpressions:
                  - key: kubernetes.io/hostname
                    operator: In
                    values:
                      - {NODE-NAME-1}
                      - {NODE-NAME-2}
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: DoNotSchedule
          labelSelector:
            matchLabels:
              postgres-operator.crunchydata.com/instance-set: instance1
```

To place the data of each replica on a specific node and path, set **spec.instances[].storage.local** with exactly one entry per replica instead:

```yaml
spec:
  instances:
    - name: instance1
      replicas: 2
      storage:
        capacity: 20Gi
        className: {STORAGE-CLASS-NAME}
        local:
          - node: {NODE-NAME-1}
            path: /opt/local-path-provisioner/postgresql/instance1-0
          - node: {NODE-NAME-2}
            path: /opt/local-path-provisioner/postgresql/instance1-1
```

For every entry, the Cennso PostgreSQL Instance creates a statically provisioned local Persistent Volume on that node and path, with the capacity of **spec.instances[].storage.capacity** and the `Retain` reclaim policy. The Persistent Volumes are kept when the Cennso PostgreSQL Instance is deleted. Each replica binds to one of these volumes and is scheduled onto the node that holds it, so a replica never lands on a node that is not listed. The scheduler decides which replica takes which node. To pin a specific replica to a specific node, use one instance set per node with `replicas: 1`.

> [!IMPORTANT]
> The directories specified in **spec.instances[].storage.local[].path** must exist on the nodes before you deploy the Cennso PostgreSQL Instance. For more information, read the [Deploy Cennso PostgreSQL](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-postgresql.md) guide.

## PostgreSQL cluster size

The Cennso Database extension allows you to deploy and manage database clusters consisting of multiple database instances. The number of PostgreSQL instances that run in an instance set is set by the following configuration option:

```yaml
spec:
  instances:
    - name: instance1
      replicas: 2
```

One of the instances is the primary and the others are read replicas. You can define several instance sets with different settings, for example to place the replicas on different groups of nodes.

> [!IMPORTANT]
> An in-place major-version upgrade requires `2` or more replicas. For more information, see the [Major-version upgrades](#major-version-upgrades) section.

## Storage configuration

The storage configuration section allows you to specify the size and the storage class of the requested storage for the PostgreSQL instances of an instance set:

```yaml
spec:
  instances:
    - name: instance1
      replicas: 2
      storage:
        capacity: 20Gi
        className: {STORAGE-CLASS-NAME}
```

The chosen storage class should be available on the target cluster and mapped to node-local paths if you rely on a provisioner such as [local-path-provisioner](https://github.com/rancher/local-path-provisioner). The storage class is created by the Cennso PostgreSQL Operator. For more information, see the [Storage configuration](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-postgresql-operator.md#storage-configuration) section.

Without **spec.instances[].storage.local**, the volume is provisioned dynamically by the storage class on the node where the Pod is scheduled. In this case, no directories need to exist on the nodes in advance. To place the volumes on specific nodes and paths, see the [Scheduling and placement configuration](#scheduling-and-placement-configuration) section.

To keep the [write-ahead log](https://www.postgresql.org/docs/current/wal-intro.html) (WAL) on a separate volume, for example on faster disks, add the optional **spec.instances[].walStorage** configuration option to the instance set:

```yaml
spec:
  instances:
    - name: instance1
      replicas: 2
      storage:
        capacity: 20Gi
        className: {STORAGE-CLASS-NAME}
      walStorage:
        capacity: 5Gi
        className: {WAL-STORAGE-CLASS-NAME}
```

The storage class dynamically provisions the write-ahead log volume on the node where the Pod is scheduled. Without **spec.instances[].walStorage**, the write-ahead log stays on the data volume. You can add or remove **spec.instances[].walStorage** on a running instance set. The PostgreSQL Pods restart one by one, and the write-ahead log moves to the new volume, or back to the data volume, which must have capacity for it. The database operator deletes the removed write-ahead log volume.

## TLS certificates configuration

The database operator manages the TLS certificates used for the encrypted connections to the PostgreSQL server. By default, it creates a [Certificate](https://cert-manager.io/docs/usage/certificate/) Custom Resource managed by [cert-manager](https://cert-manager.io/) for the CA, the PostgreSQL server, and all other components that need secury connections.

The certificates are valid for one year by default. cert-manager renews them `30` days before they expire, and the PostgreSQL and PgBouncer Pods load the renewed certificates without a restart.

Using the following configuration options, you can change the validity of the certificates managed by the database operator:

```yaml
spec:
  tls:
    certValidityDuration: 2160h
    caValidityDuration: 17520h
```

The **spec.tls.certValidityDuration** configuration option defines the validity of the PostgreSQL server, replication, PgBouncer and PostgreSQL Pod certificates. The **spec.tls.caValidityDuration** configuration option defines the validity of the CA certificate. Both values must be longer than `720h`, because cert-manager rejects a certificate whose validity is shorter than the renewal period of `30` days.

> [!IMPORTANT]
> When you change the validity of an existing PostgreSQL cluster, cert-manager does not reissue the certificates that are still valid. The new validity applies when a certificate is renewed or issued for the first time. To apply the new validity immediately, delete the following Kubernetes Secrets in the namespace of the PostgreSQL cluster, where `POSTGRESQL-INSTANCE` is the value of the **metadata.name** from the `PostgreSQLInstance`:
>
> - `{POSTGRESQL-INSTANCE}-cluster-ca-cert`
> - `{POSTGRESQL-INSTANCE}-cluster-cert`
> - `{POSTGRESQL-INSTANCE}-replication-cert`
> - `{POSTGRESQL-INSTANCE}-pgbouncer-frontend-tls`
> - `{POSTGRESQL-INSTANCE}-{INSTANCE-SET-NAME}-{SUFFIX}-certs`

Using the following configuration options, you can configure the references to the Kubernetes Secrets which contain your own TLS certificates and keys instead of the certificates managed by the database operator:

```yaml
spec:
  tlsSecretName: "tls-secret"
  replicationTLSSecretName: "replication-tls-secret"
```

The **spec.tlsSecretName** configuration option defines the Kubernetes Secret with the certificate used by the PostgreSQL server and PgBouncer. The **spec.replicationTLSSecretName** configuration option defines the Kubernetes Secret with the client certificate of the replication user. By default, **spec.tlsSecretName** is an empty string, which means the certificates managed by the database operator are used. You cannot combine **spec.tls** with **spec.tlsSecretName**. 

Both certificates must be issued by the same CA, and both configuration options must be set together. These Kubernetes Secrets must exist in the target cluster, in the same namespace where you deployed your PostgreSQL instances. Each Kubernetes Secret must contain the `ca.crt`, `tls.crt` and `tls.key` keys, and the server certificate must contain the DNS names of the primary, replicas, and PgBouncer Services in its Subject Alternative Names. For more information on how to create custom TLS certificates, read the [Use your own TLS certificates](https://docs.cennso.com/cennso/cennso-db/latest/operation-guides/cennso-postgresql-certificates.md#use-your-own-tls-certificates) section.

For more information on how to switch an existing PostgreSQL cluster to your own TLS certificates, read the [Manage TLS certificates](https://docs.cennso.com/cennso/cennso-db/latest/operation-guides/cennso-postgresql-certificates.md) document.

## PostgreSQL resources configuration

You can specify [resources](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) for the PostgreSQL instances of an instance set using the following configuration options:

```yaml
spec:
  instances:
    - name: instance1
      resources:
        requests:
          cpu: 500m
          memory: 1Gi
        limits:
          cpu: 2
          memory: 4Gi
```

## Environment variables

You can add environment variables to the containers of the PostgreSQL Pods of an instance set and to the [PgBouncer](https://www.pgbouncer.org/) Pods using the following configuration options:

```yaml
spec:
  instances:
    - name: instance1
      env:
        - name: TZ
          value: Europe/Berlin
        - name: {VARIABLE-NAME}
          valueFrom:
            secretKeyRef:
              name: {SECRET-NAME}
              key: {SECRET-KEY}
      envFrom:
        - configMapRef:
            name: {CONFIGMAP-NAME}
  proxy:
    pgBouncer:
      env:
        - name: TZ
          value: Europe/Berlin
      envFrom:
        - secretRef:
            name: {SECRET-NAME}
```

The **spec.instances[].env** and **spec.proxy.pgBouncer.env** entries set single variables, with a literal **env[].value** or an **env[].valueFrom** source such as a key of a Kubernetes Secret or ConfigMap. The **spec.instances[].envFrom** and **spec.proxy.pgBouncer.envFrom** entries import every key of a Secret or ConfigMap as a variable. The Secrets and ConfigMaps must exist in the target cluster, in the same namespace as the PostgreSQL instances. The variables are added to every container of the Pod after the variables set by the database operator, so do not use a name the operator already sets, such as `PGDATA` or `PATRONI_NAME`.

For more information, see the [official Kubernetes documentation](https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/).

## PostgreSQL server configuration

You can set PostgreSQL server settings using the **spec.postgresql.parameters** configuration option. The keys are the setting names as in `postgresql.conf`, so you can provide any setting of the PostgreSQL version in use:

```yaml
spec:
  postgresql:
    parameters:
      max_connections: 200
      shared_buffers: 1GB
      work_mem: 8MB
      log_min_duration_statement: 500
```

The settings are applied through [Patroni](https://docs.cennso.com/cennso/cennso-db/latest/troubleshooting/patroni.md) to the primary and to every replica, so all PostgreSQL servers of the instance run with the same configuration. A setting that PostgreSQL can only change on restart, such as `max_connections` or `shared_buffers`, causes a rolling restart of the PostgreSQL pods. Other settings take effect on reload.

The following settings are managed by the database operator and Patroni. Any values specified for these settings in **spec.postgresql.parameters** are replaced.

- `ssl`, `ssl_cert_file`, `ssl_key_file`, `ssl_ca_file`
- `unix_socket_directories`
- `archive_mode`, `archive_command`
- `track_commit_timestamp`
- `listen_addresses`, `port`, `cluster_name`
- `data_directory`, `config_file`, `hba_file`, `ident_file`
- `hot_standby`, `wal_log_hints`

A setting that PostgreSQL does not recognize is rejected during reload and reported in the logs of the `database` container.

For more information about the settings you can configure, see the [official PostgreSQL documentation](https://www.postgresql.org/docs/current/runtime-config.html).

## PostgreSQL extensions

You can enable the [`pg_stat_statements`](https://www.postgresql.org/docs/current/pgstatstatements.html) extension, which tracks execution statistics of all SQL statements, using the following configuration option:

```yaml
spec:
  postgresql:
    extensions:
      pgStatStatements:
        enabled: true
```

When you enable it, the database operator creates the extension in every database of the instance.

> [!IMPORTANT]
> Enabling or disabling the extension causes a rolling restart of the PostgreSQL pods and, if the metrics exporter is enabled, a restart of the exporter pods. Disabling it removes the extension from every database together with the collected statistics.

If the metrics exporter is enabled, it also exposes the number of executed statements, the number of rows, and the execution time, grouped by statement type. For more information, see the [Metrics](https://docs.cennso.com/cennso/cennso-db/latest/observability/cennso-postgresql-metrics.md#statements-by-type) document.

Keep in mind the following limitations of the statements by type metrics:

- The statement type is the first word of the statement, so statements that start with `WITH` are counted as `with` instead of the command that follows. Statements that start with a comment or a parenthesis are counted as `other`.
- The extension keeps the statistics of up to `5000` distinct statements. When an application runs more distinct statements, the extension removes the least used ones, and the metrics show short spikes. To keep more statements, increase the `pg_stat_statements.max` setting using the **spec.postgresql.parameters** configuration option. A change of this setting causes a rolling restart of the PostgreSQL pods.

## Failover timing

[Patroni](https://docs.cennso.com/cennso/cennso-db/latest/troubleshooting/patroni.md) runs the PostgreSQL servers and performs the failover. The primary holds a leader lease and renews it on every check. When the lease expires, a replica is promoted. You can tune the timing using the following configuration options:

```yaml
spec:
  patroni:
    syncPeriodSeconds: 10
    leaderLeaseDurationSeconds: 30
```

The **spec.patroni.syncPeriodSeconds** sets how often Patroni checks the state of PostgreSQL and renews the lease. The **spec.patroni.leaderLeaseDurationSeconds** sets how long the lease stays valid without a renewal. A shorter lease gives a faster failover after a primary fails, and a higher risk of an unwanted failover when the primary is only slow, for example under heavy load. The lease must be at least the sync period plus `20` seconds, which is the time Patroni allows for two retries of a failed check.

The liveness probe of the PostgreSQL pods is derived from these values. It runs every **spec.patroni.syncPeriodSeconds**, times out after half of it, and fails after **spec.patroni.leaderLeaseDurationSeconds** divided by **spec.patroni.syncPeriodSeconds** attempts.

For more information, see the [Patroni documentation](https://patroni.readthedocs.io/en/latest/dynamic_configuration.html).

## Major-version upgrades

> [!IMPORTANT]
> A major-version upgrade causes downtime. Due to the limitations of the Percona Operator for PostgreSQL, all PostgreSQL instances of the cluster are stopped while `pg_upgrade` runs, and the database is unavailable until the upgrade finishes.

To perform an in-place PostgreSQL major-version upgrade, for example from PostgreSQL `16` to `18`, change **spec.image.tag** of the `PostgreSQLInstance` CR to a tag of the higher major version:

```yaml
spec:
  image:
    tag: "v18.3-2"
```

A tag change within the same major version, for example from `v18.3-2` to `v18.4-1`, is not an upgrade. The database operator performs a rolling restart of the instance Pods with the new image. A tag with a lower major version than the running one is rejected, because `pg_upgrade` cannot move data back to an earlier major version.

For a step-by-step procedure, see the [Upgrade a database](https://docs.cennso.com/cennso/cennso-db/latest/operation-guides/cennso-postgresql-upgrade.md) document.

The upgrade uses two container images that you can configure with the following configuration options:

```yaml
spec:
  upgrade:
    jobImage: {UPGRADE-JOB-IMAGE}
    pgBackRestImage: {PGBACKREST-IMAGE}
```

## Additional services and tools

In addition to the PostgreSQL itself, the `PostgreSQLInstance` CR controls the following components:

- [PgBouncer](#pgbouncer-configuration)
- [Prometheus PostgreSQL exporter](#prometheus-postgresql-exporter-configuration)

The following sections provide information about the configuration of these tools and services.

### PgBouncer configuration

To connect to the database instances, the Cennso PostgreSQL Instance deploys the PgBouncer connection pooler. You can configure it using the following configuration options:

```yaml
spec:
  proxy:
    pgBouncer:
      replicas: 2
      image: {PGBOUNCER-IMAGE}
      resources:
        requests:
          cpu: 100m
          memory: 128Mi
        limits:
          cpu: 500m
          memory: 256Mi
      priorityClassName: {PRIORITY-CLASS-NAME}
```

The optional **spec.proxy.pgBouncer.priorityClassName** names a [PriorityClass](https://kubernetes.io/docs/concepts/scheduling-eviction/pod-priority-preemption/) for the PgBouncer Pods, which must exist on the target cluster.

Clients should connect through the PgBouncer Kubernetes [service](https://kubernetes.io/docs/concepts/services-networking/service/) rather than directly to a PostgreSQL Pod. PgBouncer pools and limits the number of active PostgreSQL connections, and connecting directly bypasses that pooling. You can configure the service using the following configuration options:

```yaml
spec:
  proxy:
    pgBouncer:
      expose:
        type: LoadBalancer
        annotations:
          custom-annotation: custom-value
        labels:
          custom-label: custom-value
        loadBalancerClass: {LOAD-BALANCER-CLASS}
        loadBalancerSourceRanges:
          - 10.0.0.0/8
```

The **spec.proxy.pgBouncer.expose.type** is one of:

- `ClusterIP`
- `NodePort`
- `LoadBalancer`

The **spec.proxy.pgBouncer.expose.loadBalancerClass** and **spec.proxy.pgBouncer.expose.loadBalancerSourceRanges** configuration options only apply to a `LoadBalancer` service.

The optional **spec.proxy.pgBouncer.config** map holds settings for the `[pgbouncer]` section of `pgbouncer.ini`. For example:

```yaml
spec:
  proxy:
    pgBouncer:
      config:
        pool_mode: transaction
        max_client_conn: "500"
        default_pool_size: "20"
```

The database operator writes these settings into the configuration file it generates for PgBouncer. Changes are applied to the running PgBouncer Pods without validation, so an invalid setting can make PgBouncer unavailable. For more information about the available settings, see the [official documentation](https://www.pgbouncer.org/config.html).

The database operator sets several `[pgbouncer]` settings. A value in **spec.proxy.pgBouncer.config** replaces the operator's value for the same setting. Avoid overriding these settings if not necessary. The table lists the values the Percona Operator for PostgreSQL sets:

| Setting | Operator value | Effect of overriding it |
|---|---|---|
| `ignore_startup_parameters` | `extra_float_digits` | Safe, keep `extra_float_digits` for JDBC clients |
| `auth_file` | Operator-managed authentication file | Breaks client authentication |
| `auth_query` | `SELECT username, password from pgbouncer.get_auth($1)` | Breaks client authentication |
| `auth_user` | Operator-managed PgBouncer role | Breaks client authentication |
| `client_tls_sslmode` | `require` | Weakens or breaks client TLS |
| `client_tls_cert_file` | Operator-managed certificate file | Breaks client TLS |
| `client_tls_key_file` | Operator-managed key file | Breaks client TLS |
| `client_tls_ca_file` | Operator-managed CA file | Breaks client TLS |
| `listen_addr` | `*` | PgBouncer stops listening on the Pod address |
| `listen_port` | The PgBouncer port of the cluster | The Service no longer reaches PgBouncer |
| `server_tls_sslmode` | `verify-full` | Weakens or breaks TLS to PostgreSQL |
| `server_tls_ca_file` | Operator-managed CA file | Breaks TLS to PostgreSQL |
| `unix_socket_dir` | Empty, the root filesystem is read-only | PgBouncer fails to start |
| `auth_type` | Set only when LDAP authentication is configured | Breaks LDAP authentication |
| `auth_hba_file` | Set only when LDAP authentication is configured | Breaks LDAP authentication |

You cannot override these settings with **spec.proxy.pgBouncer.config**:

- `conffile`
- `admin_users`

When a client opens a connection, it can pass PostgreSQL session settings in the connection request, for example `search_path`. PgBouncer calls these startup parameters and rejects a connection with a startup parameter it does not know. To accept such a parameter, add it to one of the following settings:

- `ignore_startup_parameters` accepts the parameter and discards it.
- `track_extra_parameters` accepts the parameter and applies it to the connection.

The `extra_float_digits` entry set by the database operator must stay in `ignore_startup_parameters`, otherwise JDBC clients fail to connect. For example:

```yaml
spec:
  proxy:
    pgBouncer:
      config:
        ignore_startup_parameters: "extra_float_digits, search_path"
        track_extra_parameters: "search_path"
```

### Prometheus PostgreSQL exporter configuration

The `PostgreSQLInstance` CR allows deployment of the [Prometheus PostgreSQL exporter](https://github.com/percona/postgres_exporter) for monitoring the PostgreSQL database clusters. You can enable it with:

```yaml
spec:
  metricsExporter:
    enabled: true
```

For more information, see [Enable metrics collector](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-postgresql-observability.md).
