> 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/troubleshooting/cennso-postgresql-memory-monitoring.md).

# PostgreSQL memory monitoring

The Cennso Database extension provides rich capabilities for monitoring the database instances deployed and managed by it. The database metrics exported by the [Prometheus PostgreSQL exporter](https://github.com/percona/postgres_exporter) might be insufficient to troubleshoot problems with high memory consumption. In this case, you can use the metrics that the exporter already provides together with new metrics based on [custom SQL queries](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-postgresql-observability.md#metrics-based-on-custom-queries).

A PostgreSQL instance uses memory in two ways:

- Shared memory, which is allocated once when the PostgreSQL server starts. Most of it is the buffer cache, sized by the [`shared_buffers`](https://www.postgresql.org/docs/current/runtime-config-resource.html#GUC-SHARED-BUFFERS) parameter.
- Memory of each connection. Every client connection is served by its own server process, called a backend, which allocates memory for the queries it runs. For example, each sort or hash operation of a query can use up to [`work_mem`](https://www.postgresql.org/docs/current/runtime-config-resource.html#GUC-WORK-MEM) of memory, and maintenance operations, such as `VACUUM` or `CREATE INDEX`, can use up to [`maintenance_work_mem`](https://www.postgresql.org/docs/current/runtime-config-resource.html#GUC-MAINTENANCE-WORK-MEM) of memory.

The shared memory does not grow beyond its configured size, so constantly growing memory consumption usually comes from the connections: either there are more connections, or queries are using more memory.

## Memory usage overview

The postgres-exporter exposes the PostgreSQL server parameters as `pg_settings_*` metrics, and the number of connections as the `pg_stat_activity_count` metric. The memory-related parameters are converted to bytes, for example:

- `pg_settings_shared_buffers_bytes`
- `pg_settings_work_mem_bytes`
- `pg_settings_maintenance_work_mem_bytes`
- `pg_settings_max_connections`

To see the memory used by the connections, check the RSS line in the **Memory usage (WS + RSS + Cache)** panel of the [official dashboard](https://docs.cennso.com/cennso/cennso-db/latest/observability/cennso-postgresql-dashboard.md) of the Cennso Database extension. RSS contains the private memory of the processes in the `database` container: the connections, the PostgreSQL background processes, and [Patroni](https://docs.cennso.com/cennso/cennso-db/latest/troubleshooting/patroni.md). The shared memory, including the buffer cache, is counted as page cache and is not part of RSS.

To see the number of connections by state, you can add the following [promql](https://prometheus.io/docs/prometheus/latest/querying/basics/) query to the dashboard:

```promql
sum(pg_stat_activity_count{
    k8s_cluster_name="$CLUSTER_NAME",
    namespace="$POSTGRESQL_NAMESPACE",
    postgresql_instance=~"$POSTGRESQL_INSTANCE"
  }) by (postgresql_instance, state)
```

If RSS grows together with the number of connections, reduce the number of connections, for example using [PgBouncer](https://www.pgbouncer.org/). If it grows without new connections, look for the queries that use a lot of memory, as described in the [Memory of a single connection](#memory-of-a-single-connection) section.

## Shared memory allocations

To see what the shared memory consists of, use the [`pg_shmem_allocations`](https://www.postgresql.org/docs/current/view-pg-shmem-allocations.html) view.

You can build a custom metric `pg_custom_shmem_allocated_bytes` using the following configuration of the postgres-exporter:

```yaml
spec:
  metricsExporter:
    enabled: true
    customQueries: |
      pg_custom_shmem:
        query: |
          SELECT COALESCE(name, '<free>') AS name,
                 allocated_size AS allocated_bytes
          FROM pg_shmem_allocations
          WHERE allocated_size > 1048576
        metrics:
          - name:
              usage: "LABEL"
          - allocated_bytes:
              usage: "GAUGE"
              description: "Shared memory allocated, by allocation name"
```

After this metric is enabled, you can add the following promql query to the dashboard:

```promql
topk by (postgresql_instance) (5, pg_custom_shmem_allocated_bytes{
    k8s_cluster_name="$CLUSTER_NAME",
    namespace="$POSTGRESQL_NAMESPACE",
    postgresql_instance=~"$POSTGRESQL_INSTANCE",
    name!="Buffer Blocks"
  })
```

The `Buffer Blocks` allocation is the buffer cache itself, so it is excluded from the query above.

## Memory of a single connection

PostgreSQL does not expose the memory of other connections as a view, so it cannot be collected as a metric. Instead, you can write the memory usage of a connection to the PostgreSQL server log using the [`pg_log_backend_memory_contexts`](https://www.postgresql.org/docs/current/functions-admin.html#FUNCTIONS-ADMIN-SIGNAL) function. To do that, execute the following steps:

1. Find the process ID of the suspicious connection, for example, the longest running queries:

   ```bash
   kubectl exec -n {NAMESPACE-WITH-DATABASE-INSTANCES} {POSTGRESQL-POD-NAME} -c database -- psql -c "SELECT pid, usename, datname, state, now() - query_start AS duration, left(query, 60) AS query FROM pg_stat_activity WHERE backend_type = 'client backend' AND state <> 'idle' ORDER BY duration DESC NULLS LAST LIMIT 10;"
   ```

2. Write the memory usage of the connection to the server log:

   ```bash
   kubectl exec -n {NAMESPACE-WITH-DATABASE-INSTANCES} {POSTGRESQL-POD-NAME} -c database -- psql -c "SELECT pg_log_backend_memory_contexts({PID});"
   ```

3. Find the current log file of the server:

   ```bash
   kubectl exec -n {NAMESPACE-WITH-DATABASE-INSTANCES} {POSTGRESQL-POD-NAME} -c database -- psql -Atc "SELECT current_setting('data_directory') || '/' || pg_current_logfile();"
   ```

4. Read the memory contexts from the log file:

   ```bash
   kubectl exec -n {NAMESPACE-WITH-DATABASE-INSTANCES} {POSTGRESQL-POD-NAME} -c database -- grep -E "\[{PID}\] LOG:  (level: [12];|Grand total)" {LOG-FILE}
   ```

   The output is similar to the following:

   ```
   2026-10-27 11:36:11.520 UTC [136] LOG:  level: 1; TopMemoryContext: 99456 total in 5 blocks; 7512 free (13 chunks); 91944 used
   2026-10-27 11:36:11.520 UTC [136] LOG:  level: 2; CacheMemoryContext: 1048576 total in 8 blocks; 516624 free (0 chunks); 531952 used
   ...
   2026-10-27 11:36:11.521 UTC [136] LOG:  Grand total: 1855080 bytes in 237 blocks; 780272 free (318 chunks); 1074808 used
   ```

   Each line shows a memory context of the connection and its size. The command shows only the top two levels of the memory contexts. To see all of them, use the `"\[{PID}\] LOG:  (level|Grand total)"` pattern instead. The `Grand total` line shows the total memory used by the connection.
