This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: pgbouncer-1-24-named-prepared-statement-decollision-invariant

PgBouncer 1.24 Named Prepared Statement Session De-Collision Invariant

Enforces deterministic statement naming isolation and client-driver configurations under PgBouncer 1.24 transaction pooling. Precludes cross-tenant query plan pollution, cache collisions, and statement leakage caused by static statement identifiers across multiplexed backend server sessions. Mandates parameterized unnamed execution or cryptographically collision-free tenant-namespaced statement hashing.

Prohibited Anti-Pattern: Cross-Session Collision and Plan Poisoning via Static Named Prepared Statements in Transaction-Pooled PgBouncer

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PgBouncer 1.24 Named Prepared Statement Session De-Collision Invariant - Enforces deterministic statement naming isolation and client-driver configurations under PgBouncer 1.24 transaction pooling. Precludes cross-tenant query plan pollution, cache collisions, and statement leakage caused by static statement identifiers across multiplexed backend server sessions. Mandates parameterized unnamed execution or cryptographically collision-free tenant-namespaced statement hashing.
globs: src/database/**/*.{ts,js,py,go}, src/infra/**/*.{ts,js,py,go}, src/repositories/**/*.{ts,js,py,go}, config/pgbouncer*.ini
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pgbouncer-1-24-named-prepared-statement-decollision-invariant"
---

# PgBouncer 1.24 Named Prepared Statement Session De-Collision Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Cross-Session Collision and Plan Poisoning via Static Named Prepared Statements in Transaction-Pooled PgBouncer

## System Constraints
You are a Principal Database Infrastructure Engineer enforcing strict PgBouncer 1.24+ named prepared statement transaction isolation invariants. PgBouncer 1.24 introduces transaction-level prepared statement tracking; however, client drivers utilizing static statement names across distinct tenant tenants or schemas create critical race conditions, query plan cache collisions, and silent data exposure via search_path contamination. You must enforce driver configurations that either employ unnamed extended query protocol statements or enforce tenant-isolated, cryptographically hashed statement namespaces.

## Strict Guidelines
- Engineers MUST ALWAYS omit client-side static statement names (e.g., `name: 'get_user_by_id'`) when operating against transaction-mode PgBouncer pools, defaulting to unnamed extended query protocol statements.
- Engineers MUST NOT execute manual `DEALLOCATE` or `DISCARD ALL` commands from client code, as this de-synchronizes PgBouncer 1.24's internal statement tracker and triggers state machine panics.
- Code MUST isolate multi-tenant prepared statements by deriving unique statement names from both tenant tenant context and normalized query digests when client-side naming is explicitly required by protocol drivers.
- Services MUST ensure that `search_path` mutations are accompanied by connection re-initialization or tenant-isolated pool partitioning to prevent plan cache reuse across multi-tenant schemas.
- Components NEVER share raw pooled connections across concurrent async tasks without resetting per-transaction state or isolating driver-level statement caches.

## Bad vs Good Implementations
### Node.js/pg Transaction Pooling: Eliminating Static Statement Name Collisions

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using a static statement name ('fetch_user_record') across multiple tenants in PgBouncer transaction pooling contaminates the backend prepared statement cache. If another tenant runs the same query with a different search_path or schema definition, PgBouncer's 1.24 tracking layer or PostgreSQL backend will reuse the cached physical plan, leading to cross-tenant data corruption or 'prepared statement already exists' errors.
```typescript
import { Pool } from 'pg';

const pool = new Pool({ connectionString: process.env.PGBOUNCER_TRANSACTION_POOL_URL });

export async function getTenantUserData(tenantId: string, userId: string) {
  const client = await pool.connect();
  try {
    // ANTI-PATTERN: Setting search_path dynamically while using a static statement name
    // in PgBouncer transaction pooling leads to statement cache collision
    // and cross-tenant plan pollution across pooled backend connections.
    await client.query(`SET search_path TO tenant_${tenantId}`);
    
    const result = await client.query({
      name: 'fetch_user_record',
      text: 'SELECT id, email, secret_token FROM users WHERE id = $1',
      values: [userId]
    });
    
    return result.rows[0];
  } finally {
    client.release();
  }
}
```

#### Production Standard (Correct)
> **Standard**: Removing static query naming forces PostgreSQL and PgBouncer 1.24 to utilize unnamed extended query protocol execution, preventing state collision across pooled transactions. Eliminating dynamic search_path mutations in favor of explicit tenant predicate filtering precludes plan poisoning across shared backend connections.
```typescript
import { Pool, QueryConfig } from 'pg';
import { createHash } from 'crypto';

const pool = new Pool({
  connectionString: process.env.PGBOUNCER_TRANSACTION_POOL_URL,
  // PgBouncer 1.24 supports unnamed prepared statements natively without collisions
});

export async function getTenantUserData(tenantId: string, userId: string) {
  const client = await pool.connect();
  try {
    // INVARIANT FIX: Pass tenant_id explicitly into the query predicate rather than
    // mutating search_path, and omit static 'name' property to leverage unnamed protocol queries.
    const query: QueryConfig = {
      text: 'SELECT id, email, secret_token FROM users WHERE tenant_id = $1 AND id = $2',
      values: [tenantId, userId]
      // 'name' is intentionally omitted: unnamed queries are natively de-collided
    };

    const result = await client.query(query);
    return result.rows[0] ?? null;
  } finally {
    client.release();
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PgBouncer 1.24 Named Prepared Statement Session De-Collision Invariant

PgBouncer 1.24 Named Prepared Statement Session De-Collision Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic statement naming isolation and client-driver configurations under PgBouncer 1.24 transaction pooling. Precludes cross-tenant query plan pollution, cache collisions, and statement leakage caused by static statement identifiers across multiplexed backend server sessions. Mandates parameterized unnamed execution or cryptographically collision-free tenant-namespaced statement hashing. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Cross-Session Collision and Plan Poisoning via Static Named Prepared Statements in Transaction-Pooled PgBouncer Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftCross-Session Collision and Plan Poisoning via Static Named Prepared Statements in Transaction-Pooled PgBouncerCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS omit client-side static statement names (e.g., `name

Engineers MUST ALWAYS omit client-side static statement names (e.g., `name: 'get_user_by_id'`) when operating against transaction-mode PgBouncer pools, defaulting to unnamed extended query protocol statements.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT execute manual `DEALLOCATE` or `DISCARD ALL` commands from client code, as this de-synchronizes PgBouncer 1.24's internal statement tracker and triggers state machine panics.

Engineers MUST NOT execute manual `DEALLOCATE` or `DISCARD ALL` commands from client code, as this de-synchronizes PgBouncer 1.24's internal statement tracker and triggers state machine panics.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST isolate multi-tenant prepared statements by deriving unique statement names from both tenant tenant context and normalized query digests when client-side naming is explicitly required by protocol drivers.

Code MUST isolate multi-tenant prepared statements by deriving unique statement names from both tenant tenant context and normalized query digests when client-side naming is explicitly required by protocol drivers.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST ensure that `search_path` mutations are accompanied by connection re-initialization or tenant-isolated pool partitioning to prevent plan cache reuse across multi-tenant schemas.

Services MUST ensure that `search_path` mutations are accompanied by connection re-initialization or tenant-isolated pool partitioning to prevent plan cache reuse across multi-tenant schemas.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER share raw pooled connections across concurrent async tasks without resetting per-transaction state or isolating driver-level statement caches.

Components NEVER share raw pooled connections across concurrent async tasks without resetting per-transaction state or isolating driver-level statement caches.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is PgBouncer 1.24 Named Prepared Statement Session De-Collision Invariant critical for AI coding assistants?

Enforces deterministic statement naming isolation and client-driver configurations under PgBouncer 1.24 transaction pooling. Precludes cross-tenant query plan pollution, cache collisions, and statement leakage caused by static statement identifiers across multiplexed backend server sessions. Mandates parameterized unnamed execution or cryptographically collision-free tenant-namespaced statement hashing. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Cross-Session Collision and Plan Poisoning via Static Named Prepared Statements in Transaction-Pooled PgBouncer) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

PgBouncer