> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Why does PostgreSQL show more connections from ClickHouse than postgresql_connection_pool_size?

> The pool size of 16 applies to one pool, and every PostgreSQL table, database, dictionary and ClickHouse replica has its own pool. How to count the pools and reduce the connections.

[`postgresql_connection_pool_size`](https://clickhouse.com/docs/reference/settings/session-settings/postgresql-connection#postgresql_connection_pool_size) (default `16`) limits the connections of one pool, not of the whole ClickHouse server.
ClickHouse creates a separate pool for every table, database and dictionary that points to PostgreSQL, and every ClickHouse server has its own set of pools.
PostgreSQL sees the sum of all of them.

## What has its own pool

| Object in ClickHouse | Pools |
| - | - |
| Table with `ENGINE = PostgreSQL` | One per table |
| Database with `ENGINE = PostgreSQL` | One per database, shared by all its tables |
| Dictionary with `SOURCE(POSTGRESQL(...))` | One per dictionary |
| `postgresql` table function | A new one for every call |

Two more factors multiply the number:

* **PostgreSQL addresses.** If an object lists several PostgreSQL hosts (`host1|host2` in the address, or several `replica` entries in a dictionary source), it keeps a pool of `postgresql_connection_pool_size` connections for each address.
* **ClickHouse replicas.** Each ClickHouse server keeps its own pools. In a cluster, and in a ClickHouse Cloud service with several replicas, every replica that runs queries against PostgreSQL opens its own connections.

The upper bound is therefore `pool size x pools x PostgreSQL addresses x ClickHouse replicas`.
For example, five `PostgreSQL` tables with the default pool size on three replicas can hold up to 5 x 16 x 3 = 240 connections.

## How a pool opens and keeps connections

* A pool starts empty. A query takes one connection for each PostgreSQL table that it reads from or inserts into. A new connection is opened only when all connections of the pool are in use.
* When the query finishes, the connection goes back to the pool and stays open for the next query. The pool doesn't close idle connections, so a pool holds as many connections as the highest number of queries that used it at the same time, up to the pool size. They show up as idle sessions in PostgreSQL.
* When all connections of a pool are in use, a query waits for a free one: [`postgresql_connection_pool_wait_timeout`](https://clickhouse.com/docs/reference/settings/session-settings/postgresql-connection#postgresql_connection_pool_wait_timeout) milliseconds (default `5000`) per attempt, and it makes [`postgresql_connection_pool_retries`](https://clickhouse.com/docs/reference/settings/session-settings/postgresql-connection#postgresql_connection_pool_retries) attempts (default `2`) before it fails.
* If ClickHouse finds a pooled connection closed or broken, it opens a new one in its place. If the old connection was lost on the network without PostgreSQL being notified, PostgreSQL can keep showing the old session until its own keepalive or session timeouts remove it.

## Count the pools and the connections

The following query lists the tables and dictionaries that have a pool on the server where you run it.
In this example the server has two `PostgreSQL` tables and one dictionary with a PostgreSQL source:

```sql theme={null}
SELECT
    database,
    name,
    engine
FROM system.tables
WHERE (engine = 'PostgreSQL'
        AND database NOT IN (SELECT name FROM system.databases WHERE engine = 'PostgreSQL'))
    OR (engine = 'Dictionary' AND create_table_query ILIKE '%SOURCE(POSTGRESQL(%')
ORDER BY database, name;
```

```text theme={null}
   ┌─database─┬─name─────────────┬─engine─────┐
1. │ default  │ pg_customers     │ PostgreSQL │
2. │ default  │ pg_orders        │ PostgreSQL │
3. │ default  │ pg_products_dict │ Dictionary │
   └──────────┴──────────────────┴────────────┘
```

The subquery leaves out the tables of databases with the `PostgreSQL` engine. They also report the `PostgreSQL` table engine, but they share the one pool of their database. Count each such database once; they are listed by `SELECT name FROM system.databases WHERE engine = 'PostgreSQL'`.

On the PostgreSQL side, count the sessions of the user that ClickHouse connects as, by client address and state:

```sql theme={null}
SELECT client_addr, state, count(*) AS connections
FROM pg_stat_activity
WHERE usename = 'pg_user'
GROUP BY client_addr, state
ORDER BY connections DESC;
```

## Reduce the number of connections

**Lower the pool size of a table.** Since ClickHouse 26.7 the `PostgreSQL` table engine accepts the pool settings in a `SETTINGS` clause. `ALTER TABLE ... MODIFY SETTING` isn't supported for this engine, so re-create an existing table:

```sql theme={null}
CREATE OR REPLACE TABLE pg_orders
(
    id Int32,
    amount Float64
)
ENGINE = PostgreSQL('postgres-host:5432', 'shop', 'orders', 'pg_user', 'pg_password')
SETTINGS
    postgresql_connection_pool_size = 4,
    postgresql_connection_pool_auto_close_connection = 1;

SHOW CREATE TABLE pg_orders;
```

```text theme={null}
CREATE TABLE default.pg_orders
(
    `id` Int32,
    `amount` Float64
)
ENGINE = PostgreSQL('postgres-host:5432', 'shop', 'orders', 'pg_user', '[HIDDEN]')
SETTINGS postgresql_connection_pool_size = 4, postgresql_connection_pool_auto_close_connection = 1
```

The `postgresql` table function accepts the same settings as its last argument, for example `SETTINGS postgresql_connection_pool_size = 2`.
A table created without the clause takes the query-level `postgresql_connection_pool_*` settings that are in effect when it is created.

A `PostgreSQL` database and a dictionary don't store pool settings in their definitions. When the server loads them after a restart, they take the query-level settings from its default settings profile, so change the pool size there. For a table or a database created from a [named collection](https://clickhouse.com/docs/concepts/features/configuration/server-config/named-collections.md#named-collections-for-accessing-postgresql-database), the collection can carry the pool settings as well.

**Close idle connections.** With [`postgresql_connection_pool_auto_close_connection`](https://clickhouse.com/docs/reference/settings/session-settings/postgresql-connection#postgresql_connection_pool_auto_close_connection) set to `1`, a connection is closed when the query returns it to the pool, so no idle sessions stay open in PostgreSQL. The cost is a new connection to PostgreSQL for every query.

**Use fewer pools.** All tables of a [`PostgreSQL` database](https://clickhouse.com/docs/reference/engines/database-engines/postgresql) share the pool of the database, so one database instead of many separate `PostgreSQL` tables needs one pool instead of many.

A smaller pool makes concurrent queries on the same object wait for each other, so size it for the number of queries that read from PostgreSQL at the same time.

## Related pages

* [`PostgreSQL` table engine](https://clickhouse.com/docs/reference/engines/table-engines/integrations/postgresql#settings): the pool settings and their defaults
* [`postgresql` table function](https://clickhouse.com/docs/reference/functions/table-functions/postgresql)
* [PostgreSQL dictionary source](https://clickhouse.com/docs/reference/statements/create/dictionary/sources/postgresql.md)
