I keep getting asyncpg.exceptions.ConnectionDoesNotExistError: connection was closed in the middle of operation in my Sqlalchemy application
0
votes
0
answers
264
views
I have SQLAlchemy setup with pgbouncer, my pgboucer is configured to use session mode and my sqlalchemy engine config is as follows:
engine = create_async_engine(
url=db_url,
echo=False,
pool_size=200,
max_overflow=20,
pool_timeout=30,
pool_pre_ping=True,
pool_recycle=1800,
pool_reset_on_return=None,
poolclass=AsyncAdaptedQueuePool,
connect_args={"prepared_statement_cache_size": 0, 'server_settings': {'jit': 'off'}}
)
Session = sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
autocommit=False,
)
My session usage is:
@asynccontextmanager
async def get_session_context() -> AsyncSession: # type: ignore
async with Session() as session:
if session is None:
raise Exception("Database session is None")
try:
yield session
except Exception as e:
LOGGER.error(pprint.pprint(e, indent=4, depth=4))
await session.rollback()
raise e
finally:
await session.close()
but I keep getting this error .exceptions.ConnectionDoesNotExistError: connection was closed in the middle of operation
It seems sqlalchemy closes the database connection while it is still in use. The reason why I do not think the connection is getting closed from the pgbouncer side is because I tried using sqlalchemy with the database directly and I get the same error. it seems the connection is getting closed somehow.
Asked by Starbody
(3 rep)
Feb 11, 2025, 08:50 PM