Does an unhandled exception in a FastAPI yield dependency leave a SQLAlchemy async session checked out?
0 reputation · 26 Feb 2020, 11:56 UTC
0 reputation · 26 Feb 2020, 11:56 UTC
FastAPI dependencies that use yield execute teardown code after the response, including when the endpoint raises an unhandled exception. I am using SQLAlchemy 2.0 with an async engine backed by QueuePool, and I need to determine whether an async session left open in a dependency is returned to the connection pool before the response finishes. The engine exposes pool.size(), pool.checkedin(), and pool.checkedout(), yet intermittent exhaustion indicates connections may remain checked out under concurrent load.
Does an unhandled exception in the endpoint skip the dependency teardown and leave the session checked out? Should the dependency explicitly await session.close() before yielding to keep pool_size plus max_overflow available?
No. An unhandled exception in the endpoint does not by itself skip dependency teardown. FastAPI/Starlette executes the code after yield when the dependency has been entered, including after an unhandled endpoint exception, as long as the request task is not aborted before cleanup starts. The connection is returned to the pool only when the session is explicitly released. If the dependency yields the session without await session.close() in teardown, the connection can remain checked out until garbage collection, which is non-deterministic under concurrent load and can appear as intermittent pool exhaustion.
QueuePool when the session object goes out of scope; await session.close() or an equivalent context manager is required.await session.close() before yield makes the session unusable by the endpoint.The dependency probably creates AsyncSessionLocal(), yields it, and never awaits session.close() in teardown. Under concurrent load with failing endpoints, checked-out connections accumulate faster than garbage collection reclaims them, so pool.checkedout() stays high and pool_size + max_overflow is exhausted.
from sqlalchemy.ext.asyncio import AsyncSession
async def get_session() -> AsyncSession:
session = AsyncSessionLocal()
try:
yield session
finally:
await session.close()
Equivalent form:
async def get_session() -> AsyncSession:
async with AsyncSessionLocal() as session:
yield session
yield; the endpoint would receive a closed session.pool.checkedout() before and after requests, including requests that raise unhandled exceptions, and confirm it returns to baseline after responses complete.type(engine.pool) if you need to interpret checkedout() precisely; SQLAlchemy 2.x async engines commonly adapt QueuePool through an async pool wrapper.This assumes SQLAlchemy 2.0 with an async engine and FastAPI/Starlette dependency execution. The exact meaning of pool.checkedout() depends on the async pool adapter, so treat pool metrics as indicative until you confirm the pool class. If requests are cancelled before teardown runs, cleanup may not execute; that is separate from an ordinary unhandled exception.
Are the failing requests raising exceptions after the dependency has yielded, or are they being cancelled before teardown can run? This changes whether the issue is session leakage or aborted cleanup.
Use comments to ask for clarification. Post a solution as an answer.
37,275 reputation · 26 Feb 2020, 17:38 UTC
FastAPI’s yield dependency teardown executes after the endpoint response, even when an unhandled exception propagates, as long as the request task isn’t cancelled before the exception is raised. However, if the exception aborts the task (e.g., due to cancellation or a broken wrapper), the finally block may never run, leaving the AsyncSession open and the underlying DBAPI connection checked out. To guarantee deterministic release, close the session explicitly in the finally clause, e.g. await session.close(), and verify with pool.checkedout() before and after each request.