PostgreSQL "Connection is closed" error after a few minutes of activity

Hi @shaun!

Thank you for the suggestion! Unfortunately, it seems that asyncpg doesn’t handle this parameter.

After digging up a bit, I found that there is a similar parameter server-side, tcp_keepalives_idle. If I’m looking at the value on the PostgreSQL server, it’s set at 7200 seconds (the default):

postgres=# SELECT name, setting, unit FROM pg_settings WHERE name='tcp_keepalives_idle';
        name         | setting | unit 
---------------------+---------+------
 tcp_keepalives_idle | 7200    | s

From what I understand, PostgreSQL allows the client to override some of its settings. So, this parameter can be set in the client code through the server_settings parameter. Like this:

engine = create_async_engine(
    database_url,
    connect_args={"server_settings": {"tcp_keepalives_idle": "600"}},
)

This is not very well documented in SQLAlchemy, here is the only reference that gave me an hint about this: PostgreSQL — SQLAlchemy 1.4 Documentation

I’ve set it to 10 minutes (600 seconds)… But this doesn’t solve the issue. I’m not 100% sure the parameter is actually taken into account by PostgreSQL.

I also tried to set it directly on the cluster configuration thanks to the guidance found in this topic, by using the stolonctl tool. Unfortunately, it doesn’t solve the issue neither :cry: