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

Drizzle ORM 0.38 Serverless Prepared Statement Cache Eviction & Connection Guardrail

Mandates deterministic prepared statement lifecycle management and driver-level statement cache bypassing for Drizzle ORM 0.38+ within serverless and edge runtimes. Prevents connection pool exhaustion, memory bloat across execution context freeze/thaw cycles, and PgBouncer 42P05 prepared statement collisions in pooled environments.

Prohibited Anti-Pattern: Global Unbounded Prepared Statement Caching Over Transient Serverless Handoffs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Drizzle ORM 0.38 Serverless Prepared Statement Cache Eviction & Connection Guardrail - Mandates deterministic prepared statement lifecycle management and driver-level statement cache bypassing for Drizzle ORM 0.38+ within serverless and edge runtimes. Prevents connection pool exhaustion, memory bloat across execution context freeze/thaw cycles, and PgBouncer 42P05 prepared statement collisions in pooled environments.
globs: src/db/**/*.ts, src/lib/db/**/*.ts, src/server/**/*.ts, api/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/drizzle-038-serverless-prepared-statement-cache-eviction-standard"
---

# Drizzle ORM 0.38 Serverless Prepared Statement Cache Eviction & Connection Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global Unbounded Prepared Statement Caching Over Transient Serverless Handoffs

## System Constraints
You are a Principal Backend Architect enforcing Drizzle ORM 0.38 Serverless Prepared Statement Cache Eviction Standards. Mandate stateless connection protocols, enforce disabled or bounded prepared statement handles when targeting transactional connection poolers (e.g., PgBouncer, Neon Pooler, Supabase Pooler), and ensure memory handles are deterministically pruned during serverless runtime freeze/thaw transitions.

## Strict Guidelines
- Engineers MUST ALWAYS configure the underlying driver with `prepare: false` (or connection-equivalent protocol flags) when deploying Drizzle ORM to serverless environments paired with transaction-mode connection poolers.
- Engineers MUST NOT declare named prepared queries (`.prepare('statement_name')`) at the module level in serverless functions, as duplicate statement identifiers collide across shared downstream connections (PostgreSQL error 42P05).
- Code SHOULD prefer HTTP/stateless database adapters (e.g., `@neondatabase/serverless` HTTP client, `@planetscale/database`, or Cloudflare D1/Hyperdrive) over stateful TCP pools in short-lived execution contexts.
- Services MUST explicitly clear or bound query statement references within invocation wrappers if dynamic `.prepare()` constructs are utilized.
- Components NEVER preserve open transaction handles or active query promises across serverless runtime handoffs or background suspension states.

## Bad vs Good Implementations
### Serverless Drizzle Client and Prepared Statement Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In serverless runtimes using PgBouncer/transaction poolers, the global client maintains stateful references across warm lambda freezes. Persistent named prepared statements collide when PgBouncer routes subsequent executions to another backend connection where the statement already exists or does not exist, triggering fatal 42P05 exceptions and unbounded memory retention of statement objects.
```typescript
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import { users } from './schema';
import { eq } from 'drizzle-orm';

// ANTI-PATTERN: Default connection pooling in serverless with global statement caching enabled
// Connecting to a transaction-mode pooler (e.g. Supabase port 6543, Neon pooler)
const client = postgres(process.env.DATABASE_URL!);
export const db = drizzle(client);

// ANTI-PATTERN: Module-level named prepared statement will throw 42P05 ('prepared statement already exists')
// on subsequent invocations when downstream pooler reassigns backend connections, while caching handles indefinitely
export const findUserByIdPrepared = db
  .select()
  .from(users)
  .where(eq(users.id, sql.placeholder('userId')))
  .prepare('find_user_by_id');

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

#### Production Standard (Correct)
> **Standard**: Explicitly passing `prepare: false` to the driver prevents creating and caching server-side prepared statements on pooled database instances. Restricting `max: 1` aligns with the serverless execution model, preventing pooler exhaustion and memory accumulation across invocations.
```typescript
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import { users } from './schema';
import { eq } from 'drizzle-orm';

// PRODUCTION FIX: Disable prepared statements explicitly for transaction poolers
// and limit connection pool size to 1 per serverless execution context
const client = postgres(process.env.DATABASE_URL!, {
  prepare: false, // Prevents 42P05 collisions and server-side statement memory bloat
  max: 1,
  idle_timeout: 0,
  connect_timeout: 10,
});

export const db = drizzle(client);

export async function handler(event: { userId: string }) {
  // Execute queries without server-side prepared statement retention
  // Drizzle automatically parametrizes values safely via postgres.js without backend naming collisions
  const [user] = await db
    .select({
      id: users.id,
      email: users.email,
    })
    .from(users)
    .where(eq(users.id, event.userId))
    .limit(1);

  return user ?? null;
}
```

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 0.38 Serverless Prepared Statement Cache Eviction & Connection Guardrail

Drizzle ORM 0.38 Serverless Prepared Statement Cache Eviction & Connection Guardrail defines an industrial-grade behavioral standard for backend engineering. Mandates deterministic prepared statement lifecycle management and driver-level statement cache bypassing for Drizzle ORM 0.38+ within serverless and edge runtimes. Prevents connection pool exhaustion, memory bloat across execution context freeze/thaw cycles, and PgBouncer 42P05 prepared statement collisions in pooled environments. 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: Global Unbounded Prepared Statement Caching Over Transient Serverless Handoffs 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 DriftGlobal Unbounded Prepared Statement Caching Over Transient Serverless HandoffsCritical
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 configure the underlying driver with `prepare

Engineers MUST ALWAYS configure the underlying driver with `prepare: false` (or connection-equivalent protocol flags) when deploying Drizzle ORM to serverless environments paired with transaction-mode connection 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 declare named prepared queries (`.prepare('statement_name')`) at the module level in serverless functions, as duplicate statement identifiers collide across shared downstream connections (PostgreSQL error 42P05).

Engineers MUST NOT declare named prepared queries (`.prepare('statement_name')`) at the module level in serverless functions, as duplicate statement identifiers collide across shared downstream connections (PostgreSQL error 42P05).

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 prefer HTTP/stateless database adapters (e.g., `@neondatabase/serverless` HTTP client, `@planetscale/database`, or Cloudflare D1/Hyperdrive) over stateful TCP pools in short-lived execution contexts.

Code SHOULD prefer HTTP/stateless database adapters (e.g., `@neondatabase/serverless` HTTP client, `@planetscale/database`, or Cloudflare D1/Hyperdrive) over stateful TCP pools in short-lived execution contexts.

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 explicitly clear or bound query statement references within invocation wrappers if dynamic `.prepare()` constructs are utilized.

Services MUST explicitly clear or bound query statement references within invocation wrappers if dynamic `.prepare()` constructs are utilized.

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 preserve open transaction handles or active query promises across serverless runtime handoffs or background suspension states.

Components NEVER preserve open transaction handles or active query promises across serverless runtime handoffs or background suspension states.

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 0.38 Serverless Prepared Statement Cache Eviction & Connection Guardrail critical for AI coding assistants?

Mandates deterministic prepared statement lifecycle management and driver-level statement cache bypassing for Drizzle ORM 0.38+ within serverless and edge runtimes. Prevents connection pool exhaustion, memory bloat across execution context freeze/thaw cycles, and PgBouncer 42P05 prepared statement collisions in pooled environments. 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 (Global Unbounded Prepared Statement Caching Over Transient Serverless Handoffs) 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