Understanding PDO Persistent Connection Recycling Limits for MySQL Driver
0 reputation · 02 Mar 2021, 22:07 UTC
0 reputation · 02 Mar 2021, 22:07 UTC
Goal: clarify how PDO::ATTR_PERSISTENT connections are typically recycled when using the MySQL driver, and what limits govern their reuse across PHP requests.
Constraints: the recycling policy is driver‑specific and not formally documented; connection limits depend on MySQL max_connections and PHP process lifecycle; version differences may affect behavior.
What determines when a persistent connection is returned to the pool versus closed? Does the MySQL driver apply an idle timeout or request‑based limit? How can developers predict exhaustion given varying request volumes?
35775 reputation · 03 Mar 2021, 09:47 UTC
The MySQL PDO driver returns a persistent connection to its internal pool when the PDO object is destroyed (or goes out of scope) unless the MySQL server has already closed the socket. The driver itself does not apply an idle timeout or a request-based limit; the connection stays alive for the lifetime of the PHP worker process.
PDO::ATTR_PERSISTENT => true is set, the driver keeps the underlying TCP socket open after a request ends and stores it in a per-PHP-process pool.max_connections (total connections allowed).wait_timeout or interactive_timeout expires, the next PDO usage may fail with "MySQL server has gone away" and the driver will create a new socket.max_connections; if the product approaches or exceeds it, you risk exhausting the server's connection limit.Threads_connected and SHOW PROCESSLIST for idle (Sleep) connections from your PHP hosts to verify reuse.# 1. Check PHP persistent-connection stats (requires mysqlnd)
php -r "print_r(mysqli_get_client_stats());"
# Look for 'persistent_connections' and 'connection_reused' counters.
# 2. See idle MySQL connections from your app hosts
mysql -e "SHOW PROCESSLIST;" | grep -c 'Sleep'
# 3. Test reuse: run a script that opens/closes PDO many times
# with an identical DSN and watch Threads_connected in MySQL.
This recycling behavior is not formally documented and may change between PHP versions, so verify it in your specific SAPI and PHP version before relying on it. If idle connections are being killed by server timeouts, consider disabling persistence or running a lightweight validation query before reuse.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.