This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: drizzle-multitenant-prepared-statement-cache-partitioning-drizzle-orm-mult-177

Drizzle ORM Multi-Tenant Prepared Statement Cache Partitioning Standard

Enforces strict namespacing, query plan isolation, and bounded lifecycle management for Drizzle ORM prepared statements across multi-tenant architectures. Prevents cross-tenant query plan pollution, statement collisions, and database connection memory exhaustion in shared-process multi-tenant pools.

Prohibited Anti-Pattern: Global Unpartitioned Prepared Statement Naming & Unbounded Cache Leakage in Shared Multi-Tenant Pools

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Drizzle ORM Multi-Tenant Prepared Statement Cache Partitioning Standard - Enforces strict namespacing, query plan isolation, and bounded lifecycle management for Drizzle ORM prepared statements across multi-tenant architectures. Prevents cross-tenant query plan pollution, statement collisions, and database connection memory exhaustion in shared-process multi-tenant pools.
globs: src/db/**/*.{ts,tsx}, src/repositories/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/lib/db/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/drizzle-multitenant-prepared-statement-cache-partitioning-drizzle-orm-mult-177"
---

# Drizzle ORM Multi-Tenant Prepared Statement Cache Partitioning Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global Unpartitioned Prepared Statement Naming & Unbounded Cache Leakage in Shared Multi-Tenant Pools

## System Constraints
You are a Principal Software Architect enforcing the Drizzle ORM Multi-Tenant Prepared Statement Cache Partitioning Standard. Mandate tenant-isolated prepared statement keys, verify connection pooler compatibility, and prevent memory leaks and plan contamination.

## Strict Guidelines
- Engineers MUST ALWAYS namespace explicit Drizzle `.prepare(name)` identifiers with the tenant identifier or schema context (e.g., `t_${tenantId}_${queryKey}`) when executing in schema-per-tenant or dynamic RLS environments.
- Engineers MUST NOT use un-namespaced static statement names across multi-tenant contexts, as this triggers PostgreSQL error 42P05 ('prepared statement already exists') or cross-tenant query plan cache poisoning.
- Engineers MUST NOT dynamically interpolate arbitrary runtime data (such as timestamps, UUIDs, or unhashed user inputs) into statement names, preventing unbounded prepared statement allocation and connection memory bloat.
- Services operating behind transaction-level connection poolers (e.g., PgBouncer in transaction mode, Supabase pooler) MUST disable named prepared statements or configure Drizzle with `prepare: false` unless the driver supports automatic unnamed protocol-level preparation.
- Repositories MUST encapsulate tenant database access in a tenant-aware database client factory or context that automatically enforces statement scoping and statement eviction policies.
- Components NEVER store prepared query handles in global process memory without an LRU cache or bounded eviction strategy.

## Bad vs Good Implementations
### Tenant Statement Partitioning vs Static Collision

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using a static statement name ('find_user_by_email') across concurrent tenant requests on shared connections causes collision errors ('prepared statement already exists') or serves a cached plan optimized for a different tenant's data distribution. Alternatively, appending timestamps creates memory leaks.
```typescript
import { eq } from 'drizzle-orm';
import { pgTable, text, uuid } from 'drizzle-orm/pg-core';
import { db } from './db';

export const users = pgTable('users', {
  id: uuid('id').primaryKey(),
  tenantId: text('tenant_id').notNull(),
  email: text('email').notNull(),
});

// ANTI-PATTERN: Static prepared statement name shared across all tenants.
// In a shared pool or multi-tenant schema context, this leads to prepared statement collisions
// (PostgreSQL 42P05), plan contamination across tenant boundaries, or dynamic leaks if timestamps are used.
export async function getUserByEmail(tenantId: string, email: string) {
  const prepared = db
    .select()
    .from(users)
    .where(eq(users.email, email))
    .prepare('find_user_by_email'); // Collision across tenants on shared connections

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

#### Production Standard (Correct)
> **Standard**: The statement name is deterministically scoped to the tenant context with SQL placeholders. It prevents unbounded memory creation by using a fixed key per tenant/query pair and prevents cross-tenant query plan pollution.
```typescript
import { eq, and, sql } from 'drizzle-orm';
import { pgTable, text, uuid } from 'drizzle-orm/pg-core';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';

export const users = pgTable('users', {
  id: uuid('id').primaryKey(),
  tenantId: text('tenant_id').notNull(),
  email: text('email').notNull(),
});

// PRODUCTION FIX: Partitioned deterministic naming or pooler-safe execution.
// Uses a bounded, tenant-scoped deterministic identifier. For PgBouncer transaction mode,
// avoid explicit names and rely on Drizzle's unnamed statement execution.
export class TenantUserRepository {
  constructor(private readonly tenantDb: NodePgDatabase, private readonly tenantId: string) {}

  async getUserByEmail(email: string) {
    // Bounded, deterministic namespace per tenant preventing cache pollution
    const statementName = `stmt_t_${this.tenantId.replace(/[^a-zA-Z0-9_]/g, '_')}_user_by_email`;
    
    const prepared = this.tenantDb
      .select()
      .from(users)
      .where(and(eq(users.tenantId, this.tenantId), eq(users.email, sql.placeholder('email'))))
      .prepare(statementName);

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

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 Multi-Tenant Prepared Statement Cache Partitioning Standard

Drizzle ORM Multi-Tenant Prepared Statement Cache Partitioning Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict namespacing, query plan isolation, and bounded lifecycle management for Drizzle ORM prepared statements across multi-tenant architectures. Prevents cross-tenant query plan pollution, statement collisions, and database connection memory exhaustion in shared-process multi-tenant pools. 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 Unpartitioned Prepared Statement Naming & Unbounded Cache Leakage in Shared Multi-Tenant Pools 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 Unpartitioned Prepared Statement Naming & Unbounded Cache Leakage in Shared Multi-Tenant PoolsCritical
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 namespace explicit Drizzle `.prepare(name)` identifiers with the tenant identifier or schema context (e.g., `t_${tenantId}_${queryKey}`) when executing in schema-per-tenant or dynamic RLS environments.

Engineers MUST ALWAYS namespace explicit Drizzle `.prepare(name)` identifiers with the tenant identifier or schema context (e.g., `t_${tenantId}_${queryKey}`) when executing in schema-per-tenant or dynamic RLS environments.

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 use un-namespaced static statement names across multi-tenant contexts, as this triggers PostgreSQL error 42P05 ('prepared statement already exists') or cross-tenant query plan cache poisoning.

Engineers MUST NOT use un-namespaced static statement names across multi-tenant contexts, as this triggers PostgreSQL error 42P05 ('prepared statement already exists') or cross-tenant query plan cache poisoning.

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

Engineers MUST NOT dynamically interpolate arbitrary runtime data (such as timestamps, UUIDs, or unhashed user inputs) into statement names, preventing unbounded prepared statement allocation and connection memory bloat.

Engineers MUST NOT dynamically interpolate arbitrary runtime data (such as timestamps, UUIDs, or unhashed user inputs) into statement names, preventing unbounded prepared statement allocation and connection memory bloat.

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 operating behind transaction-level connection poolers (e.g., PgBouncer in transaction mode, Supabase pooler) MUST disable named prepared statements or configure Drizzle with `prepare

Services operating behind transaction-level connection poolers (e.g., PgBouncer in transaction mode, Supabase pooler) MUST disable named prepared statements or configure Drizzle with `prepare: false` unless the driver supports automatic unnamed protocol-level preparation.

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

Repositories MUST encapsulate tenant database access in a tenant-aware database client factory or context that automatically enforces statement scoping and statement eviction policies.

Repositories MUST encapsulate tenant database access in a tenant-aware database client factory or context that automatically enforces statement scoping and statement eviction policies.

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.
6

Components NEVER store prepared query handles in global process memory without an LRU cache or bounded eviction strategy.

Components NEVER store prepared query handles in global process memory without an LRU cache or bounded eviction strategy.

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 Multi-Tenant Prepared Statement Cache Partitioning Standard critical for AI coding assistants?

Enforces strict namespacing, query plan isolation, and bounded lifecycle management for Drizzle ORM prepared statements across multi-tenant architectures. Prevents cross-tenant query plan pollution, statement collisions, and database connection memory exhaustion in shared-process multi-tenant pools. 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 Unpartitioned Prepared Statement Naming & Unbounded Cache Leakage in Shared Multi-Tenant Pools) 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