How can I properly close MySQL connection pool sockets during shutdown?
Asked by
9col_layout
I'm using mysql.connector.pooling.MySQLConnectionPool, and calling close() on connections seems to return them to the pool rather than actually closing their sockets. When the application exits, the corresponding sessions remain visible on the MySQL server until the server-side idle timeout. What is the proper way to shut down the pool and close all of its connections cleanly?
Answers
A pooled connectionโs close() usually only returns that connection to the pool, so the underlying socket remains available for reuse. Pool shutdown needs to be handled separately from normal per-request cleanup. Check whether your connector version provides a pool teardown method; otherwise, close the connections during an application shutdown hook and confirm the result with SHOW PROCESSLIST.
Reply to this answer
MySQLConnectionPool does not consistently provide a public close-all operation. A practical fallback is to keep track of checked-out connections, close them during graceful shutdown, and then clean up any remaining pooled connections. If you inspect the poolโs internal queue, call the connectorโs actual disconnect method rather than relying on close(), but be aware that this depends on implementation details.
Reply to this answer
For applications where predictable teardown matters, a pooling layer with an explicit disposal method can be easier to manage. For example, SQLAlchemyโs engine.dispose() is designed to close the poolโs underlying connections. Whichever library you use, make pool disposal an explicit shutdown step instead of waiting for the database serverโs idle timeout.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Squabble: Some versions expose internal helpers such as _remove_connections() or the poolโs internal queue, but those are private APIs and may change. Use them only if there is no supported shutdown method for your connector version.