Flask dev server with threads enabled serving a flask-sqlalchemy app becomes very unstable

Viewed 315

We are developing a Flask application that relies heavily on the flask-sqlalchemy integration module. SQLAlchemy is used to connect to our MonetDB database.

When running the application via the command

flask run

the service irregularly but often hangs on various strange database client site symptoms related to the database communication, e.g. database connection closed, failed to decode some character, and other hard to interpret errors.

I know that by default, Flask's Werkzeug development server has threads enabled and when we run the development server without threads

flask run --disable-threads

the service works like a charm without any errors.

Scanning our codebase, I think we are configuring and using flask-sqlalchemy in a straight forward way:

app = Flask(__name__)
app.config.from_object(config[environment])
db.init_app(app)

we propagate updates to the database with calls that typically look like.

...
db.create_all()
db.session.add(foo)
db.session.add(bar)
...
db.session.commit()

As far as I know the session member of the SqlAlchemy db object is a ScopedSession instance and therefore it should be a thread-local and therefore thread safe object. But nonetheless we get trouble with the above mentioned errors.

The only thing I can imagine is that sometimes database modifications are not always directly followed by a db.session.commit(), i.e. we forget to call session.commit(). But I don't see how that would lead to these multi-threading issues.

0 Answers
Related