Search code examples
pythonsqlalchemydb2database-deadlocks

Sqlalchemy how to end connection to database to prevent deadlock


In my project, I'm listening to a kafka stream and putting the message into a database. I'm currently creating a scoped session to connect to my database. Is there a proper way to close the connection after the record load in order to avoid deadlocking?

I have a try-catch-finally block that does these things, but i'm wondering which one of them is actually necessary:

        session.flush()
        session.expire_all()
        session.expunge_all()
        session.remove()
        session.close_all()

If it helps, when I'm creating the connection, I'm also using connection pools with these settings:

 ENGINE = sqlalchemy.create_engine(f'db2+ibm_db://{CONNECTION_STRING}', echo=False,
                                      pool_timeout=60, pool_recycle=30, pool_size=30, max_overflow=5,

Solution

  • session.commit() or session.close() should be sufficient to release all locks held by the session.