John Hopfensperger
John Hopfensperger

Reputation: 147

Atomic commit for multiple async sessions?

I have some async sqlalchemy code for working with postgres. Initially, the code looked like this:

async def f(session: AsyncSession):
    ...

async def g(session: AsyncSession):
    ....


await asyncio.gather(f(session), g(session))
await session.commit()

I got some error messages from sqlalchemy, indicating that AsyncSession is not safe to be used by multiple functions concurrently. So I rewrote my code like this:


await asyncio.gather(f(session_1), g(session_2))
await session_1.commit()
await session_2.commit()

But it's possible for session_1.commit() to succeed and session_2.commit() to fail, leaving the database in an invalid state.

Is there a proper way to work with multiple async connections to postgres, and rollback all the changes in case an error occurs?

Upvotes: 0

Views: 43

Answers (0)

Related Questions