This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: drizzle-pgbouncer-transaction-prepared-statements-guardrail

Drizzle ORM PgBouncer Transaction Pooling Prepared Statement Guardrail

Enforces strict deactivation of client- and server-side prepared statements when configuring Drizzle ORM with connection poolers operating in transaction mode (e.g., PgBouncer, Supabase Pooler, Neon Pooled, AWS RDS Proxy). Eliminates catastrophic 42P05 (prepared statement already exists) and 26000 (prepared statement does not exist) runtime failures, as well as cross-tenant plan pollution caused by backend connection rotation across transactions.

Prohibited Anti-Pattern: Instantiating Drizzle ORM over transaction-mode poolers with default prepared statement caching enabled

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Drizzle ORM PgBouncer Transaction Pooling Prepared Statement Guardrail - Enforces strict deactivation of client- and server-side prepared statements when configuring Drizzle ORM with connection poolers operating in transaction mode (e.g., PgBouncer, Supabase Pooler, Neon Pooled, AWS RDS Proxy). Eliminates catastrophic 42P05 (prepared statement already exists) and 26000 (prepared statement does not exist) runtime failures, as well as cross-tenant plan pollution caused by backend connection rotation across transactions.
globs: src/**/*.ts, src/**/*.tsx, lib/**/*.ts, db/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/drizzle-pgbouncer-transaction-prepared-statements-guardrail"
---

# Drizzle ORM PgBouncer Transaction Pooling Prepared Statement Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Instantiating Drizzle ORM over transaction-mode poolers with default prepared statement caching enabled

## System Constraints
You are a Principal Software Architect enforcing zero-defect connection management for Drizzle ORM against PostgreSQL transaction-mode poolers (PgBouncer, Supabase Pooler, Neon Serverless). You must enforce `{ prepare: false }` across all database driver instantiations targeting pooled connection strings. You must reject any usage of `db.query.xyz.prepare()` on pooled clients, isolate migrations to direct connections, and prevent connection-pool backend state corruption in multi-tenant environments.

## Strict Guidelines
- Engineers MUST ALWAYS explicitly pass `{ prepare: false }` to the underlying PostgreSQL driver (e.g., `postgres(connectionString, { prepare: false })`) when connecting via PgBouncer or serverless transaction poolers.
- Engineers MUST NOT invoke Drizzle's `.prepare()` method or use manual prepared statement syntax on database instances connected through transaction-mode poolers.
- Code SHOULD maintain strict separation between runtime query clients (pooled URL, `prepare: false`) and migration/admin clients (direct unpooled URL, allowing advisory locks and DDL).
- Services MUST validate at startup that any connection string resolving to pooler ports (e.g., port 6543, Neon `-pooler` domains, AWS RDS Proxy endpoints) is strictly initialized with prepared statements disabled.
- Components NEVER store or reuse prepared query handles across asynchronous execution boundaries where pooler backend reassignment can occur.

## Bad vs Good Implementations
### Configuring Postgres.js with Drizzle for PgBouncer Transaction Mode

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting `{ prepare: false }` allows postgres.js to cache prepared statement names locally while PgBouncer swaps backend connections between transactions. This causes collisions (`prepared statement "..." already exists`) or missing definitions (`prepared statement does not exist`), leading to service degradation and plan poisoning across tenant queries.
```typescript
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';

// CRITICAL FLAW: Default postgres.js config enables prepared statements.
// In PgBouncer transaction mode, re-using pooled backend connections
// will trigger Postgres error 42P05 or 26000, corrupting concurrent multi-tenant execution.
const connectionString = process.env.DATABASE_POOLER_URL!;
const client = postgres(connectionString);

export const db = drizzle(client, { schema });

// CRITICAL FLAW: Explicitly preparing a query on a transaction-pooled connection
export const getTenantUser = db.query.users
  .findFirst({ where: (u, { eq }) => eq(u.id, 1) })
  .prepare('get_tenant_user');
```

#### Production Standard (Correct)
> **Standard**: Passing `{ prepare: false }` directly instructs the driver to execute queries via the extended/simple query protocol without creating named backend prepared statements. This ensures complete immunity from connection handoff failures in PgBouncer transaction pooling.
```typescript
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';

const connectionString = process.env.DATABASE_POOLER_URL;
if (!connectionString) {
  throw new Error('DATABASE_POOLER_URL environment variable is missing.');
}

// Mandatory: Disable prepared statements for transaction-mode pooling (PgBouncer/Supabase/Neon)
const client = postgres(connectionString, {
  prepare: false,
  max: 20,
  idle_timeout: 30,
  connect_timeout: 10,
});

export const db = drizzle(client, { schema, logger: process.env.NODE_ENV === 'development' });

// Executes dynamically without registering named prepared statements on the backend connection
export async function getTenantUser(tenantId: string, userId: string) {
  return db.query.users.findFirst({
    where: (u, { eq, and }) => and(eq(u.tenantId, tenantId), eq(u.id, userId)),
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Drizzle ORM PgBouncer Transaction Pooling Prepared Statement Guardrail

Drizzle ORM PgBouncer Transaction Pooling Prepared Statement Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict deactivation of client- and server-side prepared statements when configuring Drizzle ORM with connection poolers operating in transaction mode (e.g., PgBouncer, Supabase Pooler, Neon Pooled, AWS RDS Proxy). Eliminates catastrophic 42P05 (prepared statement already exists) and 26000 (prepared statement does not exist) runtime failures, as well as cross-tenant plan pollution caused by backend connection rotation across transactions. 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: Instantiating Drizzle ORM over transaction-mode poolers with default prepared statement caching enabled 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 DriftInstantiating Drizzle ORM over transaction-mode poolers with default prepared statement caching enabledCritical
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 explicitly pass `{ prepare

Engineers MUST ALWAYS explicitly pass `{ prepare: false }` to the underlying PostgreSQL driver (e.g., `postgres(connectionString, { prepare: false })`) when connecting via PgBouncer or serverless transaction poolers.

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 invoke Drizzle's `.prepare()` method or use manual prepared statement syntax on database instances connected through transaction-mode poolers.

Engineers MUST NOT invoke Drizzle's `.prepare()` method or use manual prepared statement syntax on database instances connected through transaction-mode poolers.

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 SHOULD maintain strict separation between runtime query clients (pooled URL, `prepare

Code SHOULD maintain strict separation between runtime query clients (pooled URL, `prepare: false`) and migration/admin clients (direct unpooled URL, allowing advisory locks and DDL).

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 validate at startup that any connection string resolving to pooler ports (e.g., port 6543, Neon `-pooler` domains, AWS RDS Proxy endpoints) is strictly initialized with prepared statements disabled.

Services MUST validate at startup that any connection string resolving to pooler ports (e.g., port 6543, Neon `-pooler` domains, AWS RDS Proxy endpoints) is strictly initialized with prepared statements disabled.

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 store or reuse prepared query handles across asynchronous execution boundaries where pooler backend reassignment can occur.

Components NEVER store or reuse prepared query handles across asynchronous execution boundaries where pooler backend reassignment can occur.

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 Drizzle ORM PgBouncer Transaction Pooling Prepared Statement Guardrail critical for AI coding assistants?

Enforces strict deactivation of client- and server-side prepared statements when configuring Drizzle ORM with connection poolers operating in transaction mode (e.g., PgBouncer, Supabase Pooler, Neon Pooled, AWS RDS Proxy). Eliminates catastrophic 42P05 (prepared statement already exists) and 26000 (prepared statement does not exist) runtime failures, as well as cross-tenant plan pollution caused by backend connection rotation across transactions. 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 (Instantiating Drizzle ORM over transaction-mode poolers with default prepared statement caching enabled) 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

Drizzle