When I try to load a page that requires a DB connection it always returns a 500 the first time.
Anyway to avoid this?
Hi @Carlos, could you provide some more details?
Which language are you using, what framework? If any.
How do you connect to DB.
How many requests does your app handle? Does it happen only on the first connection after some inactivity?
This could be related to DB sleeping after some time of inactivity Databases | Koyeb
I’m using litestar, I’m connecting using SQLAchemy.
I haven’t checked the performance, as we are mainly 1 or 2 users of the app.
I think it’s very likely because of the DB sleeping… do you have any suggestion ?
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)
Thanks Lukasz_Oles! You are a hero!!!
I’m curious what would be your suggestion if it grows my user base? It might help other users that have similar issue with more users
In the SQLAlchemy docs they are describing several ways to handle connection disconnecting.
I proposed a one which will save you credits on DB usage. SA will recreate a connection if it’s older than 5m.
When you have more users and your app is used constantly, there may be a small performance impact here. We are talking about hundreds, maybe thausands users here. Using pool_pre_ping
may be better then. I wouldn’t worry about that though now.