Solved: (psycopg2.OperationalError) SSL connection has been closed unexpectedly

We use Python Flask-SQLAlchemy as our Flask project but have been experiencing some random socket timeouts when we push to our AWS environment.
We use Python Flask to develop out backedand application along with PostgreSQL AWS Multi-AZ PostgreSQL as RDS. When the DB fails over during updates/etc, errbot dies. and we start getting below error:
(psycopg2.OperationalError) SSL connection has been closed unexpectedly
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) SSL connection has been closed unexpectedly
Which is ok, there’s one error when the PG instance is switched. But it never reconnects, and every command produces output like:
(sqlalchemy.exc.InvalidRequestError) Can’t reconnect until invalid transaction is rolled back
It looked a bit like the database connection was going away, As always there’s a bit of a difference between pure SQLAlchemy and Flask-SQLAlchemy and how much Flask-SQLAlchemy helps with connections, sessions etc so it’s not always super useful.
However, it turns out as of Flask-SQLAlchemy 2.4 some changes have been made to how much/how easily you can poke at the actual underlying SQLAlchemy create_engine method, which is awesome because this is exactly what I wanted to do. And below is the simplest solution to fix such issue.
1 2 3 4 |
SQLALCHEMY_ENGINE_OPTIONS = { "pool_pre_ping": True, "pool_recycle": 300, } |
Its work perfect for me, below is the full code sample how we configure this option inĀ Flask-SQLAlchemy
1 2 3 4 |
app.config['JSON_SORT_KEYS'] = False app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {"pool_pre_ping": True, "pool_recycle": 300} app.config['SQLALCHEMY_POOL_TIMEOUT'] = 20 load_db(app) |