How can I properly close MySQL connection pool sockets during shutdown?
Asked by
lens-85mm
I'm using mysql.connector.pooling.MySQLConnectionPool and want to shut it down cleanly when my application exits. Calling close() on a connection seems to return it to the pool instead of closing the underlying socket, so the connections remain visible on the MySQL server until the server-side idle timeout. What is the recommended way to close every pooled connection, and would another pooling library be a better choice?
Answers
A connectionโs close() method usually returns that connection to the pool; it does not necessarily destroy the underlying socket. Treat pool shutdown as a separate step and make sure no code still holds references to pooled connections. You can confirm whether the server threads disappear with SHOW PROCESSLIST.
Reply to this answer
For applications that need predictable pool teardown, a higher-level pool such as SQLAlchemyโs can be easier to manage. Its engine.dispose() method is specifically intended to close the poolโs underlying connections. Whichever library you use, perform disposal as part of the applicationโs shutdown sequence rather than relying only on individual connection close() calls.
Reply to this answer
MySQLConnectionPool does not provide a consistent public close_all() API in all connector versions. A shutdown handler can track active connections, close them, and then clean up the remaining pooled connections. If you inspect internal pool structures, use caution because those attributes are private and may change between releases.
Reply to this answer
Add your answer
Answers are reviewed before publication.
+against the odds: The pool implementation may not expose a public close-all method. Some versions require explicitly disconnecting each pooled connection during application shutdown, although relying on private queue attributes is version-dependent.