This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: duckdb-wasm-memory-spilling-guardrail

DuckDB-WASM Linear Memory Arena Ceilings and Disk Spilling Guardrail

Enforces strict WebAssembly linear memory limits and Origin Private File System (OPFS)/IndexedDB disk-spilling configurations for DuckDB-WASM instances. Prevents browser tab crashes and uncatchable WebAssembly.Memory out-of-bounds faults by setting hard memory budgets and redirecting intermediate query scratch buffers to browser-backed storage.

Prohibited Anti-Pattern: Unbounded DuckDB-WASM In-Memory Execution Without Memory Limits or Scratch Filesystem Tiering

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: DuckDB-WASM Linear Memory Arena Ceilings and Disk Spilling Guardrail - Enforces strict WebAssembly linear memory limits and Origin Private File System (OPFS)/IndexedDB disk-spilling configurations for DuckDB-WASM instances. Prevents browser tab crashes and uncatchable WebAssembly.Memory out-of-bounds faults by setting hard memory budgets and redirecting intermediate query scratch buffers to browser-backed storage.
globs: src/**/duckdb*.{ts,tsx}, src/**/*worker*.{ts,tsx}, src/**/analytics/**/*.{ts,tsx}, src/**/olap/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/duckdb-wasm-memory-spilling-guardrail"
---

# DuckDB-WASM Linear Memory Arena Ceilings and Disk Spilling Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Unbounded DuckDB-WASM In-Memory Execution Without Memory Limits or Scratch Filesystem Tiering

## System Constraints
You are a Principal Engineer enforcing DuckDB-WASM Linear Memory Arena Spilling Guardrails. WebAssembly 32-bit linear memory is constrained to a hard 2GB-4GB boundary, but browser renderer processes routinely terminate tabs when heap allocations cross 1.5GB to 2GB. You must mandate strict memory ceiling configurations, OPFS/IndexedDB-backed temporary spill directories, query streaming via Arrow record batches, and strict worker-thread isolation.

## Strict Guidelines
- Engineers MUST ALWAYS configure DuckDB runtime parameters with explicit memory ceilings ('SET max_memory = <limit>') calculated as a safe fraction of available browser resources (e.g., maximum 512MB-1024MB).
- Engineers MUST ALWAYS initialize an Origin Private File System (OPFS) or IndexedDB-backed scratch mount and assign 'SET temp_directory = <path>' to enable external sorting and hash-join spilling.
- Engineers MUST ALWAYS isolate DuckDB-WASM instantiations inside a dedicated Web Worker to prevent UI thread lockups and renderer crashes.
- Engineers MUST NEVER invoke '.toArray()' or eagerly materialize full record sets into the JavaScript heap; all tabular data MUST be consumed via streaming Arrow chunk readers or Paginated LIMIT/OFFSET cursors.
- Services MUST explicitly call 'connection.close()' and release intermediate WASM buffers upon query completion or worker lifecycle termination.
- Components NEVER execute raw analytical OLAP joins directly on the main thread or without memory budget estimation guards.

## Bad vs Good Implementations
### Configuring Memory Ceilings and OPFS Disk Spilling in Web Worker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: DuckDB-WASM is instantiated without memory configuration constraints or a physical spill directory. When large datasets or heavy hash joins exceed WebAssembly linear memory boundaries (~2GB or renderer quotas), the browser process throws an unrecoverable RuntimeError: memory access out of bounds or kills the tab. Furthermore, calling .toArray() copies the entire dataset into the V8 engine heap, doubling memory pressure.
```typescript
import * as duckdb from '@duckdb/duckdb-wasm';

export async function executeQuery(sql: string) {
  // Anti-pattern: Default in-memory allocation without limits or scratch filesystem
  const JSDELIVR_BUNDLES = duckdb.getJsDelivrBundles();
  const bundle = await duckdb.selectBundle(JSDELIVR_BUNDLES);
  const worker = new Worker(bundle.mainWorker!);
  const logger = new duckdb.VoidLogger();
  const db = new duckdb.AsyncDuckDB(logger, worker);
  await db.instantiate(bundle.mainModule);

  const conn = await db.connect();
  // Unbounded memory usage on joins and aggregations leads to uncatchable WASM OOM
  const result = await conn.query(sql);
  
  // Eagerly materializes entire Arrow record set into V8 JS memory
  const rows = result.toArray();
  return rows;
}
```

#### Production Standard (Correct)
> **Standard**: Configures a rigid memory ceiling (768MB) via 'SET max_memory' and initializes an explicit persistent scratch directory via 'SET temp_directory' before running analytical queries. Result batches are streamed asynchronously rather than eagerly materialized with .toArray(), ensuring linear WebAssembly memory and V8 heap remain well below browser crash thresholds.
```typescript
import * as duckdb from '@duckdb/duckdb-wasm';
import { AsyncDuckDBConnection } from '@duckdb/duckdb-wasm';

const WASM_MEMORY_LIMIT_BYTES = 768 * 1024 * 1024; // 768MB safe ceiling
const SCRATCH_PATH = '/duckdb_scratch';

export async function initializeGuardedDuckDB(): Promise<duckdb.AsyncDuckDB> {
  const bundles = duckdb.getJsDelivrBundles();
  const bundle = await duckdb.selectBundle(bundles);
  
  // Instantiate in dedicated worker context with memory budget validation
  const worker = new Worker(bundle.mainWorker!);
  const db = new duckdb.AsyncDuckDB(new duckdb.VoidLogger(), worker);
  await db.instantiate(bundle.mainModule, bundle.pthreadWorker);

  // Mount OPFS/IndexedDB directory for temporary disk spilling
  await db.registerEmptyFileBuffer(`${SCRATCH_PATH}/spill.tmp`);
  
  const conn = await db.connect();
  try {
    // Pin memory ceiling and route spill buffers outside linear WASM memory
    await conn.query(`SET max_memory = '${Math.floor(WASM_MEMORY_LIMIT_BYTES / (1024 * 1024))}MB';`);
    await conn.query(`SET temp_directory = '${SCRATCH_PATH}';`);
    await conn.query(`SET preserve_insertion_order = false;`);
  } finally {
    await conn.close();
  }

  return db;
}

export async function* streamQueryResults(
  conn: AsyncDuckDBConnection,
  sql: string,
  batchSize: number = 2048
): AsyncGenerator<Record<string, unknown>[]> {
  // Stream results via batches instead of eager materialization into V8 heap
  const reader = await conn.send(sql);
  for await (const batch of reader) {
    const rows: Record<string, unknown>[] = [];
    const numRows = batch.numRows;
    for (let i = 0; i < numRows; i++) {
      const row = batch.get(i);
      if (row) rows.push(row.toJSON());
      if (rows.length >= batchSize) {
        yield rows;
        rows.length = 0;
      }
    }
    if (rows.length > 0) {
      yield rows;
    }
  }
}
```

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: DuckDB-WASM Linear Memory Arena Ceilings and Disk Spilling Guardrail

DuckDB-WASM Linear Memory Arena Ceilings and Disk Spilling Guardrail defines an industrial-grade behavioral standard for frontend engineering. Enforces strict WebAssembly linear memory limits and Origin Private File System (OPFS)/IndexedDB disk-spilling configurations for DuckDB-WASM instances. Prevents browser tab crashes and uncatchable WebAssembly.Memory out-of-bounds faults by setting hard memory budgets and redirecting intermediate query scratch buffers to browser-backed storage. 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 DuckDB-WASM In-Memory Execution Without Memory Limits or Scratch Filesystem Tiering 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 DuckDB-WASM In-Memory Execution Without Memory Limits or Scratch Filesystem TieringCritical
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 DuckDB runtime parameters with explicit memory ceilings ('SET max_memory = <limit>') calculated as a safe fraction of available browser resources (e.g., maximum 512MB-1024MB).

Engineers MUST ALWAYS configure DuckDB runtime parameters with explicit memory ceilings ('SET max_memory = <limit>') calculated as a safe fraction of available browser resources (e.g., maximum 512MB-1024MB).

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 ALWAYS initialize an Origin Private File System (OPFS) or IndexedDB-backed scratch mount and assign 'SET temp_directory = <path>' to enable external sorting and hash-join spilling.

Engineers MUST ALWAYS initialize an Origin Private File System (OPFS) or IndexedDB-backed scratch mount and assign 'SET temp_directory = <path>' to enable external sorting and hash-join spilling.

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 ALWAYS isolate DuckDB-WASM instantiations inside a dedicated Web Worker to prevent UI thread lockups and renderer crashes.

Engineers MUST ALWAYS isolate DuckDB-WASM instantiations inside a dedicated Web Worker to prevent UI thread lockups and renderer crashes.

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

Engineers MUST NEVER invoke '.toArray()' or eagerly materialize full record sets into the JavaScript heap

Engineers MUST NEVER invoke '.toArray()' or eagerly materialize full record sets into the JavaScript heap; all tabular data MUST be consumed via streaming Arrow chunk readers or Paginated LIMIT/OFFSET cursors.

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

Services MUST explicitly call 'connection.close()' and release intermediate WASM buffers upon query completion or worker lifecycle termination.

Services MUST explicitly call 'connection.close()' and release intermediate WASM buffers upon query completion or worker lifecycle termination.

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 execute raw analytical OLAP joins directly on the main thread or without memory budget estimation guards.

Components NEVER execute raw analytical OLAP joins directly on the main thread or without memory budget estimation guards.

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 DuckDB-WASM Linear Memory Arena Ceilings and Disk Spilling Guardrail critical for AI coding assistants?

Enforces strict WebAssembly linear memory limits and Origin Private File System (OPFS)/IndexedDB disk-spilling configurations for DuckDB-WASM instances. Prevents browser tab crashes and uncatchable WebAssembly.Memory out-of-bounds faults by setting hard memory budgets and redirecting intermediate query scratch buffers to browser-backed storage. 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 DuckDB-WASM In-Memory Execution Without Memory Limits or Scratch Filesystem Tiering) 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.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

DuckDB-WASM