CodexBloom - Programming Q&A Platform

Issue with FastAPI and Async SQLAlchemy Queries - Getting 'Session is closed' Error

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
fastapi sqlalchemy asyncio database error Python

I'm wondering if anyone has experience with I've searched everywhere and can't find a clear answer. I'm facing a frustrating issue while using FastAPI with SQLAlchemy. Whenever I try to perform async database operations, I get the `sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception; no further SQL can be emitted until the rollback is called.` or sometimes `sqlalchemy.exc.ResourceClosedError: This session is closed`. It seems to happen intermittently during concurrent requests. Here's a minimal example of my code: ```python from fastapi import FastAPI, Depends from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.orm import sessionmaker from sqlalchemy import Column, Integer, String, select from sqlalchemy.ext.declarative import declarative_base DATABASE_URL = "sqlite+aiosqlite:///./test.db" Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True, index=True) name = Column(String, index=True) engine = create_async_engine(DATABASE_URL, echo=True) AsyncSessionLocal = async_sessionmaker(bind=engine, expire_on_commit=False) app = FastAPI() async def get_db() -> AsyncSession: async with AsyncSessionLocal() as session: yield session @app.post("/users/") async def create_user(name: str, db: AsyncSession = Depends(get_db)): async with db.begin(): # This line is causing issues periodically user = User(name=name) db.add(user) await db.commit() return user ``` I've tried several things: ensuring that I'm using the async session correctly, wrapping my database calls in `async with`, and checking my FastAPI dependency injection. However, the errors still persist. Sometimes the session closes unexpectedly, especially under load, and I'm not sure how to handle it properly. I'm using FastAPI version 0.68.1 and SQLAlchemy version 1.4.22. Any insights on how to manage the session lifecycles correctly or any known issues with Async SQLAlchemy would be greatly appreciated. What am I doing wrong? For context: I'm using Python on Windows 11. Am I approaching this the right way?