PHP › PDO & Databases

How does connection pooling and persistent connections work with PDO, and what tradeoffs should be considered before enabling persistent connections?

Advanced

Answer

A persistent PDO connection, enabled through the PDO::ATTR_PERSISTENT attribute, tells PHP to attempt to reuse an existing database connection from a previous request rather than establishing a brand new connection every single time, which can reduce the overhead of connection setup for high traffic applications, but it also introduces risks such as a connection potentially carrying over unexpected state, like an uncommitted transaction, from a previous request, meaning persistent connections should be used carefully and are generally more appropriate in specific deployment configurations rather than as a universal default.
$pdo = new PDO($dsn, $username, $password, [
    PDO::ATTR_PERSISTENT => true,
]);
Real-world example A high traffic application experimenting with persistent connections to reduce database connection overhead carefully tests for any unexpected state leakage between requests before enabling the feature broadly across their production environment.

Common follow-ups: What specific risks can arise from a persistent connection carrying over state between separate requests?;How does persistent connection behavior differ depending on whether PHP is running through PHP-FPM or a long running process like Swoole?