Why FastAPI background tasks lose database sessions and how to fix it

A common FastAPI pattern passes a request-scoped database session into BackgroundTasks, which causes failures in production. Since FastAPI 0.106.0, a dependency's teardown runs right after the response is sent, so the session is already closed when the background task starts. Queries or lazy loads on that session then raise SQLAlchemy errors such as DetachedInstanceError or ResourceClosedError. The article recommends passing only primitive identifiers or serializable payloads and creating a fresh session inside the worker from an application-wide async_sessionmaker with expire_on_commit=False. It also suggests using context managers so transactions commit on success, roll back on errors, and always return connections to the pool.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in