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

Drizzle ORM Serverless Prepared Statement Bounded LRU and Eviction Standard

Enforces strict bounds and deterministic LRU eviction on prepared statements when using Drizzle ORM in ephemeral serverless and edge runtimes. Prevents V8 isolate out-of-memory crashes and upstream database connection pooler (e.g., PgBouncer, Neon) prepared statement thrashing.

Prohibited Anti-Pattern: Unbounded Dynamic Statement Preparation and Leakage Across Ephemeral Edge Connections

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Drizzle ORM Serverless Prepared Statement Bounded LRU and Eviction Standard - Enforces strict bounds and deterministic LRU eviction on prepared statements when using Drizzle ORM in ephemeral serverless and edge runtimes. Prevents V8 isolate out-of-memory crashes and upstream database connection pooler (e.g., PgBouncer, Neon) prepared statement thrashing.
globs: src/**/*.ts, src/db/**/*.ts, drizzle.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/drizzle-serverless-prepared-statement-lru-cache-guardrail"
---

# Drizzle ORM Serverless Prepared Statement Bounded LRU and Eviction Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Dynamic Statement Preparation and Leakage Across Ephemeral Edge Connections

## System Constraints
You are a Principal Software Architect enforcing the Drizzle ORM Serverless Prepared Statement LRU Cache Eviction Standard. In ephemeral serverless contexts (Vercel Edge, Cloudflare Workers, AWS Lambda), unbounded call-sites using `.prepare()` with dynamic query names or caching queries naively across warm invocations cause severe client-side heap exhaustion (128MB isolate ceiling) and database connection pooler errors (e.g., PgBouncer 'prepared statement already exists'). You must strictly enforce either disabled statement preparation for transaction-pool mode or bounded, static LRU statement caches.

## Strict Guidelines
- Engineers MUST ALWAYS pass `prepare: false` in database driver options when connecting via PgBouncer or serverless transaction-mode connection poolers unless driver-native LRU statement recycling is explicitly configured.
- Engineers MUST NOT construct dynamic statement identifiers (e.g., `.prepare(`query_${tenantId}_${Date.now()}`)`) or invoke `.prepare()` inside per-request hot paths with dynamic string interpolation.
- Code MUST manage cross-request prepared query handles using a statically bounded LRU cache with an explicit maximum entry threshold (default max: 50) and eviction callbacks.
- Services MUST declare prepared statements at module initialization time as static singletons when statement re-use is supported by the upstream connection layer.
- Components NEVER store instantiated prepared statement handles in unbounded global objects or loose Map structures across invocation lifecycles.

## Bad vs Good Implementations
### Dynamic Statement Instantiation vs. Bounded Static LRU Registry

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating unique prepared statement names per request inside ephemeral handlers rapidly exhausts client-side V8 heap memory (OOM) and thrashes server-side prepared statement caches on upstream PostgreSQL proxies (PgBouncer/Supabase/Neon), eventually triggering 'prepared statement already exists' or memory exhaustion errors.
```typescript
import { sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import { users } from './schema';

const queryClient = postgres(process.env.DATABASE_URL!);
const db = drizzle(queryClient);

// Anti-pattern: Dynamic string interpolation in prepare() inside request handler
// Unbounded memory growth in warm worker isolates + pooler statement conflicts
export async function handleRequest(userId: string) {
  const statementName = `find_user_${userId}_${Date.now()}`;
  const prepared = db
    .select()
    .from(users)
    .where(sql`${users.id} = ${userId}`)
    .prepare(statementName);

  return await prepared.execute();
}
```

#### Production Standard (Correct)
> **Standard**: The good pattern sets `prepare: false` on pooled database connections to avoid PgBouncer protocol failures, while establishing a static, parameterized prepared statement with reusable placeholders rather than dynamic runtime statement strings.
```typescript
import { eq, placeholder } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import { users } from './schema';

// Standard: In pooled serverless contexts, disable driver-level prepared statements
// or bound them to avoid pooler collision.
const queryClient = postgres(process.env.DATABASE_URL!, {
  prepare: false, // Transaction pooling safe (PgBouncer compatible)
  max: 1,
  idle_timeout: 10,
});
const db = drizzle(queryClient);

// Singleton prepared query with static identifier and parameter placeholders
const getUserByIdPrepared = db
  .select()
  .from(users)
  .where(eq(users.id, placeholder('userId')))
  .prepare('get_user_by_id');

export async function handleRequest(userId: string) {
  return await getUserByIdPrepared.execute({ userId });
}
```

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 Bounded LRU and Eviction Standard

Drizzle ORM Serverless Prepared Statement Bounded LRU and Eviction Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict bounds and deterministic LRU eviction on prepared statements when using Drizzle ORM in ephemeral serverless and edge runtimes. Prevents V8 isolate out-of-memory crashes and upstream database connection pooler (e.g., PgBouncer, Neon) prepared statement thrashing. 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: Unbounded Dynamic Statement Preparation and Leakage Across Ephemeral Edge Connections 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 DriftUnbounded Dynamic Statement Preparation and Leakage Across Ephemeral Edge ConnectionsCritical
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 pass `prepare

Engineers MUST ALWAYS pass `prepare: false` in database driver options when connecting via PgBouncer or serverless transaction-mode connection poolers unless driver-native LRU statement recycling is explicitly configured.

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 construct dynamic statement identifiers (e.g., `.prepare(`query_${tenantId}_${Date.now()}`)`) or invoke `.prepare()` inside per-request hot paths with dynamic string interpolation.

Engineers MUST NOT construct dynamic statement identifiers (e.g., `.prepare(`query_${tenantId}_${Date.now()}`)`) or invoke `.prepare()` inside per-request hot paths with dynamic string interpolation.

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 manage cross-request prepared query handles using a statically bounded LRU cache with an explicit maximum entry threshold (default max

Code MUST manage cross-request prepared query handles using a statically bounded LRU cache with an explicit maximum entry threshold (default max: 50) and eviction callbacks.

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 declare prepared statements at module initialization time as static singletons when statement re-use is supported by the upstream connection layer.

Services MUST declare prepared statements at module initialization time as static singletons when statement re-use is supported by the upstream connection layer.

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 instantiated prepared statement handles in unbounded global objects or loose Map structures across invocation lifecycles.

Components NEVER store instantiated prepared statement handles in unbounded global objects or loose Map structures across invocation lifecycles.

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 Bounded LRU and Eviction Standard critical for AI coding assistants?

Enforces strict bounds and deterministic LRU eviction on prepared statements when using Drizzle ORM in ephemeral serverless and edge runtimes. Prevents V8 isolate out-of-memory crashes and upstream database connection pooler (e.g., PgBouncer, Neon) prepared statement thrashing. 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 (Unbounded Dynamic Statement Preparation and Leakage Across Ephemeral Edge Connections) 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