Thanks Jose_Manuel_Jurado, this was useful for us to. In our scenario we were using sqlalchemy (2.x), pyodbc and Azure MSSQL and had the same issues you highlighted above. We resolved the issue by doing 2 distinct things:
- Turn off pyodbc pooling. An explanation from the sqlalchemy documentation: https://docs.sqlalchemy.org/en/20/dialects/mssql.html#pyodbc-pooling-connection-close-behavior
import pyodbc
pyodbc.pooling = False
- Recycle the sqlalchemy pool after 25mins (1500 secs) of inactivity. This ensures that the Azure gateway does not close down a connection that sqlalchemy thinks is still alive. An explanation from the sqlalchemy documentation: https://docs.sqlalchemy.org/en/20/core/engines.html#sqlalchemy.create_engine.params.pool_recycle
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False},
pool_recycle=1500
)