This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: drizzle-orm-serverless-prepared-statement-deallocation-standard

Drizzle ORM Serverless Prepared Statement & Session State Deallocation Standard

Enforces deterministic deallocation of prepared statements and transaction-mode pooling compliance in Drizzle ORM across serverless micro-VM runtimes. Eliminates PostgreSQL 42P05 duplicate statement collisions, session state pollution, and connection starvation on PgBouncer, Neon, and AWS RDS Proxy during warm container reuse.

Prohibited Anti-Pattern: Persisting server-side prepared statement handles across warm serverless micro-VM invocations connected to transaction poolers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Drizzle ORM Serverless Prepared Statement & Session State Deallocation Standard - Enforces deterministic deallocation of prepared statements and transaction-mode pooling compliance in Drizzle ORM across serverless micro-VM runtimes. Eliminates PostgreSQL 42P05 duplicate statement collisions, session state pollution, and connection starvation on PgBouncer, Neon, and AWS RDS Proxy during warm container reuse.
globs: src/db/**/*.ts, src/lib/db/**/*.ts, src/api/**/*.ts, src/functions/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/drizzle-orm-serverless-prepared-statement-deallocation-standard"
---

# Drizzle ORM Serverless Prepared Statement & Session State Deallocation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Persisting server-side prepared statement handles across warm serverless micro-VM invocations connected to transaction poolers

## System Constraints
You are a Principal Backend Architect enforcing strict database connection resilience standards for Drizzle ORM in serverless environments. You must guarantee that prepared statements are never persisted across warm micro-VM invocations when using transaction poolers like PgBouncer or RDS Proxy. Mandate appropriate driver flags (`prepare: false`), strict container-level connection sizing (`max: 1`), and deterministic session state deallocation hooks.

## Strict Guidelines
- Engineers MUST ALWAYS set `prepare: false` in the underlying database driver configuration (e.g., `postgres.js`, `pg`) when operating behind a transaction-mode connection pooler (PgBouncer, Supabase Transaction Pooler, Neon, RDS Proxy).
- Engineers MUST NOT create globally scoped, statically named Drizzle prepared statements using `.prepare('static_name')` in serverless execution paths, as pooled connections will throw SQLSTATE 42P05 (`prepared statement already exists`).
- Code MUST restrict serverless database connection pool configurations to `max: 1` per micro-VM container to prevent connection exhaustion and out-of-order session contamination across concurrent asynchronous operations.
- Services MUST implement explicit deallocation or session cleanups (`DEALLOCATE ALL` or driver connection lifecycle hooks) whenever explicit raw prepared statements or session-level advisory locks are executed within an invocation.
- Components NEVER re-instantiate Drizzle ORM client instances inside standard request handler bodies; clients must be lazily initialized as immutable module-scoped singletons with statement preparation explicitly disabled.

## Bad vs Good Implementations
### Postgres.js and Drizzle ORM Configuration for Serverless + PgBouncer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default driver configurations use client-side caching of server-side prepared statements. In serverless functions sharing connection poolers (PgBouncer in transaction mode), the backend Postgres process changes per transaction. Attempting to execute the named statement on a physical connection where it was not declared causes missing statement errors, while hitting a connection where it was declared causes '42P05: prepared statement already exists'. Additionally, `max: 10` exhausts database connection limits when serverless functions scale.
```typescript
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import { users } from './schema';
import { eq } from 'drizzle-orm';

// ANTI-PATTERN: Default postgres configuration enables prepared statements.
// In warm micro-VMs behind PgBouncer in transaction mode, static statement names
// persist on pooled physical connections, causing 42P05 crashes on subsequent calls.
const queryClient = postgres(process.env.DATABASE_URL!, {
  max: 10 // Risk of connection exhaustion across Lambda instances
});
const db = drizzle(queryClient);

// Bad: Static named prepared statement in serverless scope
const findUserPrepared = db
  .select()
  .from(users)
  .where(eq(users.id, 1))
  .prepare('find_user_by_id');

export async function handler(event: { userId: number }) {
  return await findUserPrepared.execute();
}
```

#### Production Standard (Correct)
> **Standard**: Setting `prepare: false` instructs the driver to execute queries directly via the simple query protocol or anonymous statements without cataloging them by name on the server. Setting `max: 1` ensures each serverless container limits concurrency to a single connection, eliminating connection pool starvation on warm restarts and preventing connection drift.
```typescript
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import { users } from './schema';
import { eq } from 'drizzle-orm';

// PRODUCTION INVARIANT: Disable prepared statements when using transaction poolers.
// Restrict max pool size to 1 to safeguard against warm Lambda socket multiplication.
const client = postgres(process.env.DATABASE_URL!, {
  prepare: false, // Critical: bypasses server-side prepared statements entirely
  max: 1,         // Standard for serverless: 1 active connection per container
  idle_timeout: 20,
  connect_timeout: 10,
});

export const db = drizzle(client);

export async function handler(event: { userId: number }) {
  // Queries run inline without persisting statement state across warm VM invocations
  return await db
    .select()
    .from(users)
    .where(eq(users.id, event.userId))
    .execute();
}
```

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: Drizzle ORM Serverless Prepared Statement & Session State Deallocation Standard

Drizzle ORM Serverless Prepared Statement & Session State Deallocation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic deallocation of prepared statements and transaction-mode pooling compliance in Drizzle ORM across serverless micro-VM runtimes. Eliminates PostgreSQL 42P05 duplicate statement collisions, session state pollution, and connection starvation on PgBouncer, Neon, and AWS RDS Proxy during warm container reuse. 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: Persisting server-side prepared statement handles across warm serverless micro-VM invocations connected to transaction poolers 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 DriftPersisting server-side prepared statement handles across warm serverless micro-VM invocations connected to transaction poolersCritical
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 set `prepare

Engineers MUST ALWAYS set `prepare: false` in the underlying database driver configuration (e.g., `postgres.js`, `pg`) when operating behind a transaction-mode connection pooler (PgBouncer, Supabase Transaction Pooler, Neon, RDS Proxy).

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 create globally scoped, statically named Drizzle prepared statements using `.prepare('static_name')` in serverless execution paths, as pooled connections will throw SQLSTATE 42P05 (`prepared statement already exists`).

Engineers MUST NOT create globally scoped, statically named Drizzle prepared statements using `.prepare('static_name')` in serverless execution paths, as pooled connections will throw SQLSTATE 42P05 (`prepared statement already exists`).

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 restrict serverless database connection pool configurations to `max

Code MUST restrict serverless database connection pool configurations to `max: 1` per micro-VM container to prevent connection exhaustion and out-of-order session contamination across concurrent asynchronous operations.

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 implement explicit deallocation or session cleanups (`DEALLOCATE ALL` or driver connection lifecycle hooks) whenever explicit raw prepared statements or session-level advisory locks are executed within an invocation.

Services MUST implement explicit deallocation or session cleanups (`DEALLOCATE ALL` or driver connection lifecycle hooks) whenever explicit raw prepared statements or session-level advisory locks are executed within an invocation.

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 re-instantiate Drizzle ORM client instances inside standard request handler bodies

Components NEVER re-instantiate Drizzle ORM client instances inside standard request handler bodies; clients must be lazily initialized as immutable module-scoped singletons with statement preparation explicitly 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is Drizzle ORM Serverless Prepared Statement & Session State Deallocation Standard critical for AI coding assistants?

Enforces deterministic deallocation of prepared statements and transaction-mode pooling compliance in Drizzle ORM across serverless micro-VM runtimes. Eliminates PostgreSQL 42P05 duplicate statement collisions, session state pollution, and connection starvation on PgBouncer, Neon, and AWS RDS Proxy during warm container reuse. 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 (Persisting server-side prepared statement handles across warm serverless micro-VM invocations connected to transaction poolers) 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