agentleFS
AnyOrgNameAnyOrgName/php-skills/skills/databases/connection-pooling/SKILL.md

connection-pooling

Skill4 starsChanged 4 months agoMITView on GitHub

Reuse database connections instead of opening one per request — persistent connections under PHP-FPM, external poolers (ProxySQL, PgBouncer, RDS Proxy), and sizing pools against the server's connection limit. Use when the user sees per-request overhead from opening a fresh DB connection (TCP handshake, TLS, auth) and wants to reuse connections to cut latency; the user hits "Too many connections" errors, or the database is saturated by more client connections than it can serve, and needs to bound and pool them; the user is deciding how to reuse connections given their runtime — PHP-FPM, Swoole/RoadRunner workers, or serverless — and wants the right strategy. Keywords: connection-pooling, persistent-connections, performance, database, php-fpm, proxysql, pgbouncer, max-connections, pdo.

2 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

7 rules. About 0 are common, 3 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Do not add pooling or persistent connections to a one-shot CLI script or migration that opens one connection and exits.

    line 68
  2. Distinctive:

    Do not add an external pooler when the app comfortably fits inside max_connections and connection setup is not a measured bottleneck.

    line 70
  3. Very specific:

    Read the database max_connections, subtract headroom for admin/replicas, then divide by the number of app hosts to get a per-host worker …

    line 84
  4. Very specific:

    Keep idle timeout under the server wait_timeout, wrap the first query in a reconnect-once retry for "gone away", and alert on …

    line 88
  5. Distinctive:

    When many app instances need few concurrent server connections, put an external pooler (ProxySQL for MySQL, PgBouncer for Postgres, RDS …

    line 94
  6. Very specific:

    Use transaction-level pooling (PgBouncer transaction mode / ProxySQL multiplex) for maximum reuse only if the app avoids session-scoped …

    line 97
  7. Very specific:

    Keep the connection idle timeout on the pooler shorter than the database's wait_timeout, and validate or reconnect on a "server has gone …

    line 100

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md
<!-- generated: do not edit — source: knowledge/atoms/databases/connection-pooling/ --><!-- schema: atomVersion=3 skillVersion=2 graphVersion=1 --><!-- compile: @php-skills/compiler v1.0.0 (deterministic build) -->

Database Connection Pooling

When to use

  • The user sees per-request overhead from opening a fresh DB connection (TCP handshake, TLS, auth) and wants to reuse connections to cut latency.
  • The user hits "Too many connections" errors, or the database is saturated by more client connections than it can serve, and needs to bound and pool them.
  • The user is deciding how to reuse connections given their runtime — PHP-FPM, Swoole/RoadRunner workers, or serverless — and wants the right strategy.

When NOT to use

  • Do not add pooling or persistent connections to a one-shot CLI script or migration that opens one connection and exits.
  • Do not add an external pooler when the app comfortably fits inside max_connections and connection setup is not a measured bottleneck.

Core guidance

  • Use persistent connections under PHP-FPM — Under PHP-FPM enable persistent connections (PDO::ATTR_PERSISTENT => true or a p: DSN prefix) so each worker reuses its socket across requests instead of reconnecting on every request.
  • Size total connections below the server limit — Persistent connections multiply: FPM workers x servers must stay under the database's max_connections, leaving headroom for admin and replicas. Cap FPM pm.max_children accordingly rather than assuming pooling adds capacity.

Quick recipe

  1. Read the database max_connections, subtract headroom for admin/replicas, then divide by the number of app hosts to get a per-host worker budget. (verify: sum of pm.max_children across hosts plus headroom is below max_connections.)
  2. Set PDO::ATTR_PERSISTENT => true on the DSN and set pm.max_children to the per-host budget from step 1 so workers reuse sockets without exceeding the limit. (verify: New requests reuse existing connections and Threads_connected stays flat under load.)
  3. Keep idle timeout under the server wait_timeout, wrap the first query in a reconnect-once retry for "gone away", and alert on Threads_connected nearing max_connections. (verify: A killed backend connection recovers on the next request and the connection-count alert fires before saturation.)

Best practices

  • When many app instances need few concurrent server connections, put an external pooler (ProxySQL for MySQL, PgBouncer for Postgres, RDS Proxy on AWS) in front so hundreds of clients share a small warm backend pool
  • Use transaction-level pooling (PgBouncer transaction mode / ProxySQL multiplex) for maximum reuse only if the app avoids session-scoped state — prepared statements pinned to a session, temp tables, SET variables, advisory locks
  • Keep the connection idle timeout on the pooler shorter than the database's wait_timeout, and validate or reconnect on a "server has gone away" error so a request never inherits a dead persistent socket
  • In Swoole/RoadRunner/Octane workers, hold a real in-process connection pool and return each connection after use, rather than opening a connection per job

Anti-patterns

Anti-patternWhy it failsDo instead
Opening a new connection per query or per functionConnecting per query multiplies latency and connection count, the exact cost pooling exists to remove.Create one connection per request (or check out from a pool), inject it, and<br>reuse it for all queries in that request.
Persistent connections without resetting transaction statePersistence reuses the exact server session, so an unfinished transaction or stray SET bleeds into the next user.Ensure every request commits/rolls back and clears session state before it<br>returns, or use a pooler that resets the connection on checkin.
An unbounded pool sized to peak concurrencyPast a point more connections add context-switching and lock contention, lowering throughput instead of raising it.Set a bounded pool near the database's optimal concurrency (often a small<br>multiple of CPU cores) and let requests queue briefly for a connection.

See references/anti-patterns.md.

Common mistakes

  1. Persistent connections turn a scale-out into a connection storm — Enabling persistent connections and then scaling out FPM workers multiplies open connections (workers x hosts), which can blow past max_connections and lock everyone out. Fix: Cap pm.max_children, put an external pooler in front so app scale is decoupled from backend connections, and monitor Threads_connected against the limit.
  2. Session state leaks across requests on a persistent connection — A persistent connection carries over server-side state — an uncommitted transaction, SET session variables, temp tables, or the current database — into the next request that reuses it. Fix: Always commit or roll back before the request ends, avoid relying on session variables, and reset connection state (or disable persistence) where isolation matters.
  3. Reusing a dead connection throws "server has gone away" — A cached persistent connection can be closed by the server (idle wait_timeout, restart, failover) while the client still believes it is open, so the next query fails with error 2006 "MySQL server has gone away". Fix: Keep idle timeouts below wait_timeout, enable the client's ping/validation, and wrap the first query in a reconnect-once retry after a gone-away error.
  4. Server-side prepared statements break under transaction pooling — In PgBouncer transaction mode (or ProxySQL multiplexing), server-side prepared statements, LISTEN/NOTIFY, advisory locks, and temp tables fail because each transaction may land on a different backend connection. Fix: Use client-side/emulated prepares, avoid session-scoped features, or switch that connection to session-mode pooling.

Version notes

  • PDO persistent connections work from PHP 7.4 onward (PHP >=7.4) — PDO::ATTR_PERSISTENT and the mysqli p: DSN prefix are available on PHP 7.4 and all later versions; there is no in-language connection pool, so external poolers or worker runtimes remain the way to get true pooling.

Security

  • Keep TLS and least-privilege on pooled connections — Terminate the app-to-pooler and pooler-to-database hops over TLS, and give the pooled DB user only the privileges the app needs — do not weaken auth to make pooling easier.

Testing

  • Activation and decision behavior are verified in eval/scenarios/databases/connection-pooling.yaml.

Additional resources

  • references/anti-patterns.md
  • references/core.md
  • references/examples.md
  • references/pitfalls.md
  • references/recipes.md
  • references/version-differences.md

Knowledge graph

Related: databases/mysql-indexing, databases/transactions

<!-- graph-fragment: graph/fragments/databases/connection-pooling.yaml -->

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.