I have a Flask application that uses Flask-Sqlalchemy to handle the connections to the DB. One thing that I'm noticing in my application traces is that at the end of every request in my application, there is a postgres.connection.rollback
. In no place in my code am I performing a rollback, but one is performed on every request at the end of every request. Basically, I see the following for all requests:
-> Save record to DB
-> postgres.connection.commit
-> postgres.connection.rollback
I've looked through the Flask-Sqlalchemy documentation and the source code, but I can't seem to figure out where the extraneous rollback is occurring.
By default SQLAlchemy will call a connection's rollback
method when it is returned to a connection pool. This behaviour is documented at Reset On Return
The pool includes “reset on return” behavior which will call the rollback() method of the DBAPI connection when the connection is returned to the pool. This is so that any existing transactional state is removed from the connection, which includes not just uncommitted data but table and row locks as well. For most DBAPIs, the call to rollback() is inexpensive, and if the DBAPI has already completed a transaction, the method should be a no-op.
The default behaviour can be disabled by passing pool_reset_on_return=None
to create_engine
:
engine = create_engine(url, pool_reset_on_return=None)
This behaviour can be customised by disabling the default behaviour and providing alternative behaviour in the reset pool event handler.