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

Postgres 17 JSON_TABLE Stream Transformation Memory Bound Guardrail

Enforces bounded memory limits and cursor-driven chunking when executing PostgreSQL 17 JSON_TABLE relational projections over large JSONB streams. Prevents backend executor out-of-memory crashes and unconstrained temporary disk spills triggered by unbounded nested path evaluations.

Prohibited Anti-Pattern: Unbounded In-Memory Evaluation of Deeply Nested JSON_TABLE Projections Over Massive Document Sets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 JSON_TABLE Stream Transformation Memory Bound Guardrail - Enforces bounded memory limits and cursor-driven chunking when executing PostgreSQL 17 JSON_TABLE relational projections over large JSONB streams. Prevents backend executor out-of-memory crashes and unconstrained temporary disk spills triggered by unbounded nested path evaluations.
globs: src/db/**/*.ts, src/repositories/**/*.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-memory-guardrail-postgres-17-json-251"
---

# Postgres 17 JSON_TABLE Stream Transformation Memory Bound Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded In-Memory Evaluation of Deeply Nested JSON_TABLE Projections Over Massive Document Sets

## System Constraints
You are a Principal Backend Architect enforcing strict memory and execution boundaries for PostgreSQL 17 JSON_TABLE queries. Unbounded JSON path traversals over multi-megabyte JSONB columns exhaust backend ExecutorState contexts and trigger OOM terminations or excessive temporary spill files. Mandate transaction-scoped memory safety valves, keyset pagination or cursor streaming, bounded column lengths, and explicit error handlers on JSON path evaluations.

## Strict Guidelines
- Engineers MUST ALWAYS set transaction-local safety constraints (SET LOCAL temp_file_limit and SET LOCAL statement_timeout) before executing multi-row JSON_TABLE projections.
- Engineers MUST NOT execute JSON_TABLE on unindexed, unbounded table scans where JSONB payloads exceed 100KB without explicit keyset or cursor chunking.
- Code MUST explicitly specify bounded scalar column types (e.g., varchar(N) rather than text) and provide ERROR ON ERROR / DEFAULT ON EMPTY clauses to prevent silent memory accumulation and unparsed buffer allocations.
- Services MUST process large JSONB relational projections in bounded streaming batches (e.g., pg-cursor or keyset pagination) rather than loading entire multi-megabyte result sets into Node.js client memory.
- Components NEVER execute unconstrained NESTED PATH constructs inside JSON_TABLE queries without verifying Cartesian product cardinality limits per parent document.

## Bad vs Good Implementations
### Unbounded JSON_TABLE vs Cursor-Bounded Streaming with Safe Local Constraints

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executes an unbounded JSON_TABLE query with text projections across potentially thousands of multi-megabyte JSONB rows without transaction-level memory protections (temp_file_limit) or streaming pagination, leading to query planner worker crashes, backend OOM kills, and multi-gigabyte client memory bloat.
```typescript
import { Pool } from 'pg';

export async function extractMetricsAntiPattern(pool: Pool): Promise<any[]> {
  // Anti-pattern: Unbounded scan over unindexed large JSONB documents.
  // Evaluates deep NESTED PATH directly into memory with unbounded text columns,
  // causing PG17 executor memory context explosion and tmp file spills.
  const query = `
    SELECT 
      t.batch_id,
      jt.*
    FROM raw_ingest_events t,
    JSON_TABLE(
      t.payload,
      '$.telemetry[*]'
      COLUMNS (
        metric_name text PATH '$.name',
        metric_value float8 PATH '$.value',
        NESTED PATH '$.tags[*]'
        COLUMNS (
          tag_key text PATH '$.key',
          tag_value text PATH '$.value'
        )
      )
    ) AS jt
    WHERE t.status = 'PENDING';
  `;

  const { rows } = await pool.query(query);
  return rows;
}
```

#### Production Standard (Correct)
> **Standard**: Implements transaction-scoped safety bounds (temp_file_limit, statement_timeout), strictly bounds JSON_TABLE column sizes (varchar(64) with ERROR ON ERROR), lateral joins the projection, and streams chunks through pg-cursor to guarantee deterministic memory consumption across PostgreSQL workers and Node.js.
```typescript
import { Pool, PoolClient } from 'pg';
import Cursor from 'pg-cursor';

interface MetricRecord {
  batch_id: string;
  metric_name: string;
  metric_value: number;
  tag_key: string | null;
  tag_val: string | null;
}

export async function* extractMetricsStream(
  pool: Pool,
  chunkSize = 500
): AsyncGenerator<MetricRecord[]> {
  const client: PoolClient = await pool.connect();
  try {
    await client.query('BEGIN READ ONLY');
    // Invariant: Enforce explicit memory and spill boundaries per transaction
    await client.query("SET LOCAL temp_file_limit = '128MB'");
    await client.query("SET LOCAL statement_timeout = '45s'");

    const queryText = `
      SELECT 
        t.batch_id,
        jt.metric_name,
        jt.metric_value,
        jt.tag_key,
        jt.tag_val
      FROM raw_ingest_events t
      CROSS JOIN LATERAL JSON_TABLE(
        t.payload,
        '$.telemetry[*]'
        COLUMNS (
          metric_name varchar(64) PATH '$.name' ERROR ON ERROR,
          metric_value double precision PATH '$.value' DEFAULT 0.0 ON EMPTY ERROR ON ERROR,
          NESTED PATH '$.tags[*]'
          COLUMNS (
            tag_key varchar(64) PATH '$.key',
            tag_val varchar(255) PATH '$.value'
          )
        )
      ) AS jt
      WHERE t.status = 'PENDING'
      ORDER BY t.id ASC;
    `;

    const cursor = client.query(new Cursor<MetricRecord>(queryText));
    while (true) {
      const rows = await cursor.read(chunkSize);
      if (rows.length === 0) break;
      yield rows;
    }
    await client.query('COMMIT');
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    client.release();
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 JSON_TABLE Stream Transformation Memory Bound Guardrail

Postgres 17 JSON_TABLE Stream Transformation Memory Bound Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces bounded memory limits and cursor-driven chunking when executing PostgreSQL 17 JSON_TABLE relational projections over large JSONB streams. Prevents backend executor out-of-memory crashes and unconstrained temporary disk spills triggered by unbounded nested path evaluations. 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 Evaluation of Deeply Nested JSON_TABLE Projections Over Massive Document Sets 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 Evaluation of Deeply Nested JSON_TABLE Projections Over Massive Document SetsCritical
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 set transaction-local safety constraints (SET LOCAL temp_file_limit and SET LOCAL statement_timeout) before executing multi-row JSON_TABLE projections.

Engineers MUST ALWAYS set transaction-local safety constraints (SET LOCAL temp_file_limit and SET LOCAL statement_timeout) before executing multi-row JSON_TABLE projections.

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 execute JSON_TABLE on unindexed, unbounded table scans where JSONB payloads exceed 100KB without explicit keyset or cursor chunking.

Engineers MUST NOT execute JSON_TABLE on unindexed, unbounded table scans where JSONB payloads exceed 100KB without explicit keyset or cursor chunking.

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 explicitly specify bounded scalar column types (e.g., varchar(N) rather than text) and provide ERROR ON ERROR / DEFAULT ON EMPTY clauses to prevent silent memory accumulation and unparsed buffer allocations.

Code MUST explicitly specify bounded scalar column types (e.g., varchar(N) rather than text) and provide ERROR ON ERROR / DEFAULT ON EMPTY clauses to prevent silent memory accumulation and unparsed buffer allocations.

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 process large JSONB relational projections in bounded streaming batches (e.g., pg-cursor or keyset pagination) rather than loading entire multi-megabyte result sets into Node.js client memory.

Services MUST process large JSONB relational projections in bounded streaming batches (e.g., pg-cursor or keyset pagination) rather than loading entire multi-megabyte result sets into Node.js client 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.
5

Components NEVER execute unconstrained NESTED PATH constructs inside JSON_TABLE queries without verifying Cartesian product cardinality limits per parent document.

Components NEVER execute unconstrained NESTED PATH constructs inside JSON_TABLE queries without verifying Cartesian product cardinality limits per parent document.

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 Stream Transformation Memory Bound Guardrail critical for AI coding assistants?

Enforces bounded memory limits and cursor-driven chunking when executing PostgreSQL 17 JSON_TABLE relational projections over large JSONB streams. Prevents backend executor out-of-memory crashes and unconstrained temporary disk spills triggered by unbounded nested path evaluations. 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 Evaluation of Deeply Nested JSON_TABLE Projections Over Massive Document Sets) 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