implementing Async SQLAlchemy Queries in FastAPI - 'Connection is closed' scenarios
I've been researching this but I'm following best practices but I've been banging my head against this for hours. I'm currently developing a FastAPI application that uses SQLAlchemy for database interactions. I have implemented asynchronous queries using the `asyncpg` driver. However, I keep working with a `sqlalchemy.exc.OperationalError: (asyncpg.exceptions.InvalidCatalogName) connection is closed` behavior when I try to run multiple requests concurrently. I've set up the database connection with the `async_session` from SQLAlchemy, but it seems like the connection pool is not handling multiple requests as expected. Here's a simplified version of my setup: ```python from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.orm import sessionmaker DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname" engine = create_async_engine(DATABASE_URL, echo=True) async_session = async_sessionmaker(bind=engine, expire_on_commit=False) ``` In my endpoint, I use a dependency to get the session like this: ```python from fastapi import FastAPI, Depends app = FastAPI() async def get_db() -> AsyncSession: async with async_session() as session: yield session @app.get("/items/{item_id}") async def read_item(item_id: int, db: AsyncSession = Depends(get_db)): result = await db.execute(select(Item).where(Item.id == item_id)) item = result.scalar_one_or_none() return item ``` I tried increasing the pool size and the max overflow parameters in the engine setup, but the scenario continues: ```python engine = create_async_engine(DATABASE_URL, pool_size=20, max_overflow=0, pool_timeout=30) ``` Despite these adjustments, concurrent requests still lead to the connection being closed. I've also verified that my database is running and accessible. Any insights or suggestions on how to manage the connections more effectively in this scenario would be greatly appreciated! What's the best practice here? Cheers for any assistance!