Garbage collector's warnings while running uvicorn on Debian 11 #1417
-
We're trying to deploy FastAPI application on Linode under Debian 11. We're using SQLAlchemy and asyncpg for DB communication. We use Python 3.10.2.
We noticed that every request to the app creates a brand new DB session and that session never gets disposed. So that we quickly run out of connections:
We are using the latest versions of FastAPI, SQLAlchemy, asyncpg and uvicorn.
We were tested it on Windows 10 Pro and macOS 12.3 Monterey with either the local or remote postgres. Everything worked fine: no GC warnings and DB sessions were properly re-used and we never hit |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 4 replies
-
os, python version, I think have no impact in your issue (running several instance myself on same os / same python but on aws), it seems to me it's more tied to the way you initialize your db connection. What is weird though is that you have the issue only with uvicorn and not hypercorn: I don't know precisely the difference we have here in handling lifespan events with hypercorn but typically that's on the startup event you might want to handle the db connection initialization. Unfortunately I'm not familiar of how to handle that through sqlalchemy, maybe someone can provide another snippet, but with just asyncpg it boils down to something like:
the use
hope it helps |
Beta Was this translation helpful? Give feedback.
-
Thank you for suggestion! engine = create_async_engine(
url=...,
pool_size=...,
max_overflow=...,
pool_timeout=...
) And we're seeing that this is working properly. |
Beta Was this translation helpful? Give feedback.
-
@euri10 , we've built a small test app, but unfortunately were not able to reproduce it. It seems the issue is deeper than we thought. I will come back here if I have any thoughts on how to reproduce the issue. |
Beta Was this translation helpful? Give feedback.
-
@AlexanderPodorov Does this still happens on FastAPI 0.74.0+? See https://fastapi.tiangolo.com/release-notes/#0740 |
Beta Was this translation helpful? Give feedback.
-
Sorry, forgot to update everybody here. The issue was related to SQLAlchemy. It works well with SQLAlchemy 2.0.19. |
Beta Was this translation helpful? Give feedback.
-
Hello! async_sessionmaker(close_resets_only=False) The reason is: def _close_impl(self, invalidate: bool, is_reset: bool = False) -> None:
if not is_reset and self._close_state is _SessionCloseState.ACTIVE:
self._close_state = _SessionCloseState.CLOSED Here P.S: |
Beta Was this translation helpful? Give feedback.
Sorry, forgot to update everybody here. The issue was related to SQLAlchemy. It works well with SQLAlchemy 2.0.19.