This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-json-table-work-mem-streaming

Postgres 17 JSON_TABLE Memory Ceiling & Cursor Streaming Guardrail

Enforces bounded memory ceilings and cursor-driven streaming semantics on Postgres 17 JSON_TABLE operations. Flattening high-cardinality JSON documents without explicit transaction-scoped memory limits and server-side cursors leads to backend process termination by the OS OOM killer and Node.js heap exhaustion.

Prohibited Anti-Pattern: Unbounded In-Memory Materialization and Missing work_mem Bounds in Postgres 17 JSON_TABLE Queries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 JSON_TABLE Memory Ceiling & Cursor Streaming Guardrail - Enforces bounded memory ceilings and cursor-driven streaming semantics on Postgres 17 JSON_TABLE operations. Flattening high-cardinality JSON documents without explicit transaction-scoped memory limits and server-side cursors leads to backend process termination by the OS OOM killer and Node.js heap exhaustion.
globs: src/repositories/**/*.ts, src/database/**/*.ts, src/services/**/*.ts, src/queries/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-json-table-work-mem-streaming"
---

# Postgres 17 JSON_TABLE Memory Ceiling & Cursor Streaming Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded In-Memory Materialization and Missing work_mem Bounds in Postgres 17 JSON_TABLE Queries

## System Constraints
You are a Principal Database Architect and Backend Platform Engineer enforcing Postgres 17 JSON_TABLE stability. Postgres 17 introduces the SQL/JSON standard JSON_TABLE, which can rapidly exhaust per-backend work_mem and driver heaps when expanding deeply nested or high-volume JSON collections. You must mandate server-side streaming cursors, isolated transaction-level work_mem ceilings, strictly typed column projections with explicit PATH lengths, and keyset-bounded input batches.

## Strict Guidelines
- Engineers MUST ALWAYS execute JSON_TABLE queries over unbounded arrays using server-side cursors (e.g., pg-cursor or native DECLARE CURSOR) rather than buffering the entire result set in memory.
- Engineers MUST configure a query-scoped memory boundary using 'SET LOCAL work_mem' inside an explicit transaction block prior to running expensive JSON_TABLE transformations.
- Engineers MUST NOT execute JSON_TABLE on whole-table scans; input JSON documents MUST be filtered using indexed predicate columns or keyset cursors.
- Engineers MUST define explicit column lengths and ERROR ON ERROR / EMPTY ON EMPTY handling clauses for each projected column in the JSON_TABLE COLUMNS clause to avoid silent memory leaks or unhandled plan de-optimizations.
- Code SHOULD enforce driver-level backpressure when piping streamed rows to avoid V8 or JVM heap growth during document ingestion.
- Services MUST declare statement_timeout on transactions performing JSON_TABLE expansions to preempt connection starvation.

## Bad vs Good Implementations
### Postgres 17 JSON_TABLE Extraction: Buffered Array vs. Cursor-Streamed Batch

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing JSON_TABLE over multi-megabyte payloads in a standard client.query() call buffers all generated relational rows directly into application memory. In addition, Postgres lacks explicit work_mem governance for the operation, increasing backend OOM kill risk on concurrent executions.
```typescript
import { Pool } from 'pg';

const pool = new Pool();

// ANTI-PATTERN: Buffers millions of expanded JSON rows in Node.js memory
// without per-query work_mem controls or streaming pagination.
export async function flattenTelemetryEvents(batchId: string) {
  const client = await pool.connect();
  try {
    const query = `
      SELECT jt.event_id, jt.event_type, jt.payload
      FROM raw_ingestion_batches b,
      JSON_TABLE(
        b.payload_json, '$.events[*]'
        COLUMNS (
          event_id text PATH '$.id',
          event_type text PATH '$.type',
          payload jsonb PATH '$.data'
        )
      ) AS jt
      WHERE b.batch_id = $1;
    `;
    // Materializes entire flattened array directly into driver memory
    const { rows } = await client.query(query, [batchId]);
    return rows;
  } finally {
    client.release();
  }
}
```

#### Production Standard (Correct)
> **Standard**: Wraps JSON_TABLE execution in a transaction with explicit 'SET LOCAL work_mem' and statement timeouts. Employs pg-cursor to read bounded chunks (500 rows at a time), projecting strictly typed columns with explicit length boundaries and error fallbacks, yielding backpressure-aware chunks without memory bloat.
```typescript
import { Pool, PoolClient } from 'pg';
import Cursor from 'pg-cursor';

const pool = new Pool();
const CHUNK_SIZE = 500;

export interface FlattenedEvent {
  event_id: string;
  event_type: string;
  payload: Record<string, unknown>;
}

// PRODUCTION INVARIANT: Transaction-scoped memory caps and server-side cursor streaming
export async function* streamFlattenTelemetryEvents(
  batchId: string
): AsyncGenerator<FlattenedEvent[], void, unknown> {
  const client: PoolClient = await pool.connect();
  try {
    await client.query('BEGIN READ ONLY');
    // Bound work memory and execution time strictly for this operational scope
    await client.query("SET LOCAL work_mem = '32MB'");
    await client.query("SET LOCAL statement_timeout = '30000'");

    const sql = `
      SELECT jt.event_id, jt.event_type, jt.payload
      FROM raw_ingestion_batches b,
      JSON_TABLE(
        b.payload_json, '$.events[*]'
        COLUMNS (
          event_id VARCHAR(64) PATH '$.id' ERROR ON ERROR,
          event_type VARCHAR(64) PATH '$.type' ERROR ON ERROR,
          payload JSONB PATH '$.data' EMPTY ON EMPTY
        )
      ) AS jt
      WHERE b.batch_id = $1
    `;

    const cursor = client.query(new Cursor<FlattenedEvent>(sql, [batchId]));

    try {
      while (true) {
        const rows = await cursor.read(CHUNK_SIZE);
        if (rows.length === 0) break;
        yield rows;
      }
    } finally {
      await cursor.close();
    }

    await client.query('COMMIT');
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    client.release();
  }
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 JSON_TABLE Memory Ceiling & Cursor Streaming Guardrail

Postgres 17 JSON_TABLE Memory Ceiling & Cursor Streaming Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces bounded memory ceilings and cursor-driven streaming semantics on Postgres 17 JSON_TABLE operations. Flattening high-cardinality JSON documents without explicit transaction-scoped memory limits and server-side cursors leads to backend process termination by the OS OOM killer and Node.js heap exhaustion. 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 In-Memory Materialization and Missing work_mem Bounds in Postgres 17 JSON_TABLE Queries 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 In-Memory Materialization and Missing work_mem Bounds in Postgres 17 JSON_TABLE QueriesCritical
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 execute JSON_TABLE queries over unbounded arrays using server-side cursors (e.g., pg-cursor or native DECLARE CURSOR) rather than buffering the entire result set in memory.

Engineers MUST ALWAYS execute JSON_TABLE queries over unbounded arrays using server-side cursors (e.g., pg-cursor or native DECLARE CURSOR) rather than buffering the entire result set in memory.

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 configure a query-scoped memory boundary using 'SET LOCAL work_mem' inside an explicit transaction block prior to running expensive JSON_TABLE transformations.

Engineers MUST configure a query-scoped memory boundary using 'SET LOCAL work_mem' inside an explicit transaction block prior to running expensive JSON_TABLE transformations.

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 execute JSON_TABLE on whole-table scans

Engineers MUST NOT execute JSON_TABLE on whole-table scans; input JSON documents MUST be filtered using indexed predicate columns or keyset 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.
4

Engineers MUST define explicit column lengths and ERROR ON ERROR / EMPTY ON EMPTY handling clauses for each projected column in the JSON_TABLE COLUMNS clause to avoid silent memory leaks or unhandled plan de-optimizations.

Engineers MUST define explicit column lengths and ERROR ON ERROR / EMPTY ON EMPTY handling clauses for each projected column in the JSON_TABLE COLUMNS clause to avoid silent memory leaks or unhandled plan de-optimizations.

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

Code SHOULD enforce driver-level backpressure when piping streamed rows to avoid V8 or JVM heap growth during document ingestion.

Code SHOULD enforce driver-level backpressure when piping streamed rows to avoid V8 or JVM heap growth during document ingestion.

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

Services MUST declare statement_timeout on transactions performing JSON_TABLE expansions to preempt connection starvation.

Services MUST declare statement_timeout on transactions performing JSON_TABLE expansions to preempt connection starvation.

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 Postgres 17 JSON_TABLE Memory Ceiling & Cursor Streaming Guardrail critical for AI coding assistants?

Enforces bounded memory ceilings and cursor-driven streaming semantics on Postgres 17 JSON_TABLE operations. Flattening high-cardinality JSON documents without explicit transaction-scoped memory limits and server-side cursors leads to backend process termination by the OS OOM killer and Node.js heap exhaustion. 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 In-Memory Materialization and Missing work_mem Bounds in Postgres 17 JSON_TABLE Queries) 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

Postgres