PHP › PDO & Databases
How does connection pooling and persistent connections work with PDO, and what tradeoffs should be considered before enabling persistent connections?
AdvancedAnswer
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.