Database

Manage Database Connection Pools and PHP Workers

Size database connections around PHP worker concurrency and database capacity instead of maximizing connection counts.

Overview

Connection management affects latency, memory, and database stability. In PHP deployments, persistent connections, PHP-FPM worker counts, queue workers, and administrative jobs can combine to create more simultaneous database sessions than expected.

Start with the workload and the invariant

Estimate peak possible connections from every process class: PHP-FPM children across pools, queue workers, cron tasks, reporting jobs, and monitoring. Compare this with the database's connection limit and reserve capacity for administration and failover. A configuration that is safe for one pool may become unsafe after a second site is deployed.

Practical example

Persistent connections can reduce connection setup overhead, but they do not automatically provide a well-managed pool. They may retain session state, transaction settings, temporary tables, or locks if application code is careless. In shared hosting or multi-tenant environments, their behavior should be tested rather than enabled by default.

$pdo = new PDO(
    $dsn,
    $username,
    $password,
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]
);

Trade-offs and failure modes

Keep connection lifetime short in request-oriented PHP. Open the connection when needed, avoid holding it while calling remote APIs or rendering large files, and close out transactions on every error path. For long-running workers, reconnect safely after transient failures and ensure each job leaves session state clean.

Verification and rollout

Monitor Threads_connected, connection errors, slow queries, and the ratio of active to idle sessions. A high connection count can indicate too many workers, leaked transactions, slow queries, or a burst pattern. Increasing max_connections without measuring memory and workload can turn a connection problem into an out-of-memory incident.

Engineering checklist

Load-test with realistic concurrency and include slow database periods. Set bounded timeouts, handle connection failures explicitly, and document how the application behaves during database restart or failover. Capacity planning should use observed peaks plus a safety margin, not guesswork.

Before shipping, review the database version, storage engine, SQL mode, character set, collation, and deployment process used by the target environment. Features and DDL behavior can differ between MySQL and MariaDB releases. Validate the exact statements on a representative staging database, capture a baseline, and keep a tested recovery path for changes that affect production data.

Share this page Help other developers discover this resource.