I’ve created a sample Litestar app and was able to reproduce the issue. In the SQLAlchemy docs you can find several options for handling it.
I don’t recommend using pool_pre_ping
as it causes unnecessary connections to the database, and since we charge for time spent in the DB, it will consume your free quota.
What worked for me is setting pool_recycle=300
, which creates a new connection if the current one is older than 5 minutes. You may want to tweak it more as your user base grows.
Here is the code sample I used:
from litestar.contrib.sqlalchemy.plugins import SQLAlchemyAsyncConfig, EngineConfig
engine_config = EngineConfig(pool_recycle=300)
config = SQLAlchemyAsyncConfig(
connection_string="postgresql+asyncpg://...",
engine_config=engine_config)