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

Bun 1.2 Multi-Worker Prepared Statement Cache Coherence Standard

Enforces strict lifecycle management, bounded caching, and cross-thread schema invalidation for prepared statements within Bun 1.2 multi-threaded worker pools. Prevents off-heap memory fragmentation, unbounded native statement allocations, and stale plan execution against distributed database replicas following dynamic schema alterations or failovers.

Prohibited Anti-Pattern: Global Unbounded Statement Caching and Desynchronized Prepared Plans Across Isolated Bun Worker Threads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Multi-Worker Prepared Statement Cache Coherence Standard - Enforces strict lifecycle management, bounded caching, and cross-thread schema invalidation for prepared statements within Bun 1.2 multi-threaded worker pools. Prevents off-heap memory fragmentation, unbounded native statement allocations, and stale plan execution against distributed database replicas following dynamic schema alterations or failovers.
globs: src/**/*.worker.ts, src/**/workers/**/*.ts, src/**/db/**/*.ts, src/**/repositories/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-multiworker-prepared-statement-coherence-standard"
---

# Bun 1.2 Multi-Worker Prepared Statement Cache Coherence Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global Unbounded Statement Caching and Desynchronized Prepared Plans Across Isolated Bun Worker Threads

## System Constraints
You are a Principal Backend Engineer enforcing strict prepared statement cache coherence across isolated Bun 1.2 Web Workers (`Worker` threads). You must mandate isolated statement lifecycle handling, LRU memory bounds on native statement handles, and strict inter-worker broadcast channel invalidation protocols when database topology or schema versions advance.

## Strict Guidelines
- Engineers MUST ALWAYS isolate native prepared statement caches per worker thread and bound them with an explicit Least-Recently-Used (LRU) eviction strategy to prevent native handle leaks.
- Engineers MUST NOT share raw connection handles or native statement pointers across worker boundaries via postMessage.
- Services MUST implement a BroadcastChannel or cross-thread IPC event subscriber within every worker to instantly evict and finalize prepared statement caches upon receiving schema modification or read-replica topology migration signals.
- Code SHOULD explicitly call `.finalize()` (or equivalent driver deallocation) on evicted prepared statements to reclaim off-heap C++ memory immediately rather than relying on engine garbage collection.
- Workers NEVER execute dynamic SQL concatenations inside prepared statement keys; query templates must use parameterized placeholders and normalized static string keys for cache indexing.

## Bad vs Good Implementations
### Unbounded Static Prepared Statement Cache without Schema Sync vs. Bounded Coherent Worker Cache

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The worker instantiates an unbounded Map of compiled statements that never finalizes evicted statements. Additionally, the worker lacks an IPC invalidation listener; if DDL runs or read-replica topology shifts, the worker executes stale compiled plans against invalidated catalogs.
```typescript
import { Database, Statement } from "bun:sqlite";

// ANTI-PATTERN: Worker holds an unbounded module-level statement cache
// that never responds to schema migrations, causing stale read execution and native memory bloat
const db = new Database(process.env.DB_REPLICA_URL);
const statementCache = new Map<string, Statement>();

declare const self: Worker;

self.onmessage = (event: MessageEvent<{ query: string; params: any[] }>) => {
  const { query, params } = event.data;
  
  let stmt = statementCache.get(query);
  if (!stmt) {
    // Leaks off-heap memory as queries proliferate; ignores ALTER TABLE / DDL changes across replicas
    stmt = db.prepare(query);
    statementCache.set(query, stmt);
  }
  
  const results = stmt.all(...params);
  self.postMessage(results);
};
```

#### Production Standard (Correct)
> **Standard**: Employs an explicit LRU eviction mechanism with `.finalize()` cleanup, bounding off-heap native memory. Listens on a cross-worker `BroadcastChannel` to immediately invalidate all cached statements upon schema epoch increment, guaranteeing cache coherence across isolated Bun threads.
```typescript
import { Database, Statement } from "bun:sqlite";

interface InvalidationMessage {
  type: "SCHEMA_INVALIDATION" | "REPLICA_TOPOLOGY_CHANGE";
  schemaEpoch: number;
}

class CoherentStatementCache {
  private readonly cache = new Map<string, Statement>();
  private readonly maxEntries: number;
  private currentEpoch = 0;

  constructor(private readonly db: Database, maxEntries = 256) {
    this.maxEntries = maxEntries;
  }

  public getOrPrepare(sqlKey: string, epoch: number): Statement {
    if (epoch > this.currentEpoch) {
      this.invalidateAll();
      this.currentEpoch = epoch;
    }

    const existing = this.cache.get(sqlKey);
    if (existing) {
      this.cache.delete(sqlKey);
      this.cache.set(sqlKey, existing); // Re-insert for LRU freshness
      return existing;
    }

    if (this.cache.size >= this.maxEntries) {
      const oldestKey = this.cache.keys().next().value;
      if (oldestKey) {
        this.evict(oldestKey);
      }
    }

    const stmt = this.db.prepare(sqlKey);
    this.cache.set(sqlKey, stmt);
    return stmt;
  }

  public evict(sqlKey: string): void {
    const stmt = this.cache.get(sqlKey);
    if (stmt) {
      stmt.finalize();
      this.cache.delete(sqlKey);
    }
  }

  public invalidateAll(): void {
    for (const stmt of this.cache.values()) {
      stmt.finalize();
    }
    this.cache.clear();
  }
}

declare const self: Worker;
const db = new Database(process.env.DB_REPLICA_URL);
const statementCache = new CoherentStatementCache(db, 200);
let schemaEpoch = 0;

const syncChannel = new BroadcastChannel("db_schema_coherence");
syncChannel.onmessage = (event: MessageEvent<InvalidationMessage>) => {
  if (event.data?.type === "SCHEMA_INVALIDATION" || event.data?.type === "REPLICA_TOPOLOGY_CHANGE") {
    schemaEpoch = event.data.schemaEpoch;
    statementCache.invalidateAll();
  }
};

self.onmessage = (event: MessageEvent<{ sqlTemplate: string; params: any[] }>) => {
  const { sqlTemplate, params } = event.data;
  try {
    const stmt = statementCache.getOrPrepare(sqlTemplate, schemaEpoch);
    const results = stmt.all(...params);
    self.postMessage({ success: true, data: results });
  } catch (error) {
    self.postMessage({ success: false, error: (error as Error).message });
  }
};
```

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: Bun 1.2 Multi-Worker Prepared Statement Cache Coherence Standard

Bun 1.2 Multi-Worker Prepared Statement Cache Coherence Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict lifecycle management, bounded caching, and cross-thread schema invalidation for prepared statements within Bun 1.2 multi-threaded worker pools. Prevents off-heap memory fragmentation, unbounded native statement allocations, and stale plan execution against distributed database replicas following dynamic schema alterations or failovers. 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 Statement Caching and Desynchronized Prepared Plans Across Isolated Bun Worker Threads 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 Statement Caching and Desynchronized Prepared Plans Across Isolated Bun Worker ThreadsCritical
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 isolate native prepared statement caches per worker thread and bound them with an explicit Least-Recently-Used (LRU) eviction strategy to prevent native handle leaks.

Engineers MUST ALWAYS isolate native prepared statement caches per worker thread and bound them with an explicit Least-Recently-Used (LRU) eviction strategy to prevent native handle leaks.

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 share raw connection handles or native statement pointers across worker boundaries via postMessage.

Engineers MUST NOT share raw connection handles or native statement pointers across worker boundaries via postMessage.

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

Services MUST implement a BroadcastChannel or cross-thread IPC event subscriber within every worker to instantly evict and finalize prepared statement caches upon receiving schema modification or read-replica topology migration signals.

Services MUST implement a BroadcastChannel or cross-thread IPC event subscriber within every worker to instantly evict and finalize prepared statement caches upon receiving schema modification or read-replica topology migration signals.

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

Code SHOULD explicitly call `.finalize()` (or equivalent driver deallocation) on evicted prepared statements to reclaim off-heap C++ memory immediately rather than relying on engine garbage collection.

Code SHOULD explicitly call `.finalize()` (or equivalent driver deallocation) on evicted prepared statements to reclaim off-heap C++ memory immediately rather than relying on engine garbage collection.

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

Workers NEVER execute dynamic SQL concatenations inside prepared statement keys

Workers NEVER execute dynamic SQL concatenations inside prepared statement keys; query templates must use parameterized placeholders and normalized static string keys for cache indexing.

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 Bun 1.2 Multi-Worker Prepared Statement Cache Coherence Standard critical for AI coding assistants?

Enforces strict lifecycle management, bounded caching, and cross-thread schema invalidation for prepared statements within Bun 1.2 multi-threaded worker pools. Prevents off-heap memory fragmentation, unbounded native statement allocations, and stale plan execution against distributed database replicas following dynamic schema alterations or failovers. 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 Statement Caching and Desynchronized Prepared Plans Across Isolated Bun Worker Threads) 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

Bun