Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI sharing SQLAlchemy session across threads when using synchronous functions

Noob question about normal def path operations functions, dependencies and SQLAlchemy. Quoting the example here: https://fastapi.tiangolo.com/tutorial/sql-databases/#create-a-dependency, where the db sessions is created in get_db() (synchronous) and used in create_user() (synchronous). According to https://fastapi.tiangolo.com/async/#very-technical-details, synchronous dependencies and path operation functions are executed in a thread pool, so does this mean the same DB session object is effectively shared across 2 different threads (assuming it's not the same thread that gets re-used across the dependency and path operation function)? Could this be problematic since SQLAlchemy sessions are not thread-safe?

I may be completely misunderstanding how this works, so any clarifications would be greatly appreciated.

Thanks!

EDIT: After thinking about this more I think this should be fine because session is accessed sequentially (not concurrently) even though it's potentially by two different threads. But I'm assuming using the session like the following would be problematic?

async def func(s: Session):
  loop = asyncio.get_running_loop()
  await loop.run_in_executor(None, some_func, s)
  await loop.run_in_executor(None, some_other_func, s)
  ...
like image 218
ljiatu Avatar asked Jun 25 '26 23:06

ljiatu


1 Answers

Yes Session objects are not thread-safe, but in SQLAlchemy you actually have multiple connections, because SQLAlchemy has a connection Pooling system by default so your every other SessionLocal that you define will have own connection

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

So, No connection is shared, eveything is seperated, also SessionLocal closed just after the request. So it's not thread-safe but i don't think it could be problematic.

enter image description here

Imagine you have a endpoint and it gets 2 requests at the same time, so in this case, different connections will answer your request. Even it's not concurrent, it acts like concurrent with Pooling.

like image 126
Yagiz Degirmenci Avatar answered Jun 28 '26 21:06

Yagiz Degirmenci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!