Managing the SQLAlchemy Session in a web app (per request, commit/rollback)

Backend Live Coding November 13, 2026 python

One Session per request (or per Celery task), never global and never shared between threads.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# ======================================================================
# Q: How do you manage the Session in a web application?
#
# One Session per request (or per Celery task), never global and never shared
# between threads. Commit at the end if everything went well, rollback on
# exception, always close. expire_on_commit=False helps when you return objects
# after the commit (e.g. in the response).
# ======================================================================

engine = create_engine(settings.DATABASE_URL, pool_size=10, max_overflow=20,
                       pool_pre_ping=True)        # checks for dead connections
SessionLocal = sessionmaker(engine, expire_on_commit=False)

def get_session():                               # FastAPI dependency
    with SessionLocal() as session:
        with session.begin():                     # commit or rollback automatically
            yield session