DEV Community

Mads Hansen
Mads Hansen

Posted on

Your PostgreSQL pool may remember the previous AI request

A PostgreSQL MCP query finishes and returns its connection to the pool.

The next request borrows the same physical session.

What came with it?

  • SET ROLE
  • search_path
  • a tenant GUC
  • statement_timeout
  • prepared statements
  • temporary objects
  • advisory locks
  • an aborted or accidentally open transaction

Connection pooling improves throughput. It also turns session hygiene into a security boundary.

Prefer one short transaction per tool call. Apply trusted tenant, role, and timeout context with transaction-local settings where possible. Run the query, consume or cancel it, commit or roll back, verify cleanup, then release the connection.

If rollback or reset is uncertain, discard the connection.

RESET ALL, DISCARD ALL, proxy reset queries, and driver cleanup hooks do not have identical semantics. Choose one documented reset contract for the exact driver and pooling mode you operate.

Then test reuse adversarially:

  1. alternate tenants through a pool smaller than the worker count
  2. randomize success, SQL errors, timeouts, cancellation, and disconnects
  3. leak role, GUC, timezone, and search path deliberately
  4. verify backend PID reuse and the baseline before each query
  5. kill a worker between execution and cleanup

The dangerous failure is not always a visible error. It is request B receiving valid SQL under request A's leftover session state.

Full guide: PostgreSQL MCP connection pooling: reset session state before reuse

Top comments (0)