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

Postgres 17 JSON_TABLE Streaming Projection Memory Envelope

Governs SQL/JSON JSON_TABLE transformations in PostgreSQL 17 to eliminate backend worker out-of-memory termination during high-cardinality JSONB shredding. Mandates explicit typed projections, bounded nested path evaluations, and chunked cursor-driven ingestion to ensure transformations execute strictly within designated backend working memory limits.

Prohibited Anti-Pattern: Monolithic unpartitioned JSON_TABLE projections across unbounded JSONB datasets exhausting backend working memory and triggering OS OOM termination.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 JSON_TABLE Streaming Projection Memory Envelope - Governs SQL/JSON JSON_TABLE transformations in PostgreSQL 17 to eliminate backend worker out-of-memory termination during high-cardinality JSONB shredding. Mandates explicit typed projections, bounded nested path evaluations, and chunked cursor-driven ingestion to ensure transformations execute strictly within designated backend working memory limits.
globs: src/**/*.ts, src/**/*.pg.ts, src/repositories/**/*.ts, src/database/**/*.ts, src/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-json-table-streaming-memory-envelope"
---

# Postgres 17 JSON_TABLE Streaming Projection Memory Envelope

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Monolithic unpartitioned JSON_TABLE projections across unbounded JSONB datasets exhausting backend working memory and triggering OS OOM termination.

## System Constraints
You are a Principal Database Architect and Backend Platform Engineer enforcing Postgres 17 JSON_TABLE memory safety rules. Mandate strict memory envelopes, batched keyset streaming, precise scalar column projections, and bounded nested path depth on all SQL/JSON transformations to avoid backend process termination.

## Strict Guidelines
- Engineers MUST ALWAYS bound JSON_TABLE input sets using indexed keyset pagination or chunked batch windows instead of executing whole-table unnested projections.
- Engineers MUST NOT execute JSON_TABLE projections using unqualified wildcard path expressions (e.g., '$.*') or unconstrained recursive descent ('$..*') on deep documents.
- Code SHOULD specify exact data types with strict size envelopes (e.g., VARCHAR(64), INT, NUMERIC) rather than unbounded TEXT or nested JSONB types in JSON_TABLE COLUMNS clauses.
- Services MUST enforce explicit error handling clauses ('ERROR ON ERROR' or 'EMPTY ON ERROR') in JSON_TABLE definitions to prevent silent memory-retaining error state accumulation.
- Components NEVER join high-cardinality lateral JSON_TABLE projections directly onto wide parent tables without an intermediate materialized CTE or temp table checkpoint.

## Bad vs Good Implementations
### Postgres 17 JSON_TABLE Chunked Streaming Extraction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executes an unbounded JSON_TABLE query across the entire 'orders' table. Materializing millions of nested JSONB nodes without keyset boundaries or explicit column limits risks exhausting Postgres work_mem and memory contexts, resulting in SIGKILL from the OS OOM killer.
```typescript
import { Pool } from 'pg';

export async function exportOrderItems(pool: Pool): Promise<void> {
  // Anti-pattern: Monolithic JSON_TABLE unnest over unbounded table
  // Forces backend to allocate intermediate memory for all JSONB ASTs concurrently,
  // causing worker memory ballooning and OOM killing.
  const query = `
    SELECT 
      o.id AS order_id,
      jt.*
    FROM orders o,
    JSON_TABLE(
      o.payload,
      '$.items[*]'
      COLUMNS (
        item_id text PATH '$.id',
        sku text PATH '$.sku',
        qty text PATH '$.quantity',
        raw_meta jsonb PATH '$.metadata'
      )
    ) AS jt;
  `;
  const { rows } = await pool.query(query);
  console.log(`Exported ${rows.length} items`);
}
```

#### Production Standard (Correct)
> **Standard**: Constrains JSON_TABLE input via an isolated keyset-bounded CTE, specifies narrow scalar SQL types with size bounds to control tuple descriptor footprint, and uses 'EMPTY ON ERROR' to prevent intermediate exception state allocations.
```typescript
import { Pool } from 'pg';

interface KeysetCursor {
  lastId: number;
  batchSize: number;
}

export async function exportOrderItemsStreaming(
  pool: Pool,
  cursor: KeysetCursor
): Promise<number> {
  // Production Invariant: Bounded keyset window with strict scalar sizing and EMPTY ON ERROR
  const query = `
    WITH bounded_batch AS (
      SELECT id, payload
      FROM orders
      WHERE id > $1
      ORDER BY id ASC
      LIMIT $2
    )
    SELECT 
      b.id AS order_id,
      jt.item_id,
      jt.sku,
      jt.quantity
    FROM bounded_batch b,
    JSON_TABLE(
      b.payload,
      '$.items[*]'
      EMPTY ON ERROR
      COLUMNS (
        item_id   BIGINT        PATH '$.id',
        sku       VARCHAR(32)   PATH '$.sku',
        quantity  INTEGER       PATH '$.quantity'
      )
    ) AS jt;
  `;

  const { rows } = await pool.query(query, [cursor.lastId, cursor.batchSize]);
  return rows.length;
}
```

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: Postgres 17 JSON_TABLE Streaming Projection Memory Envelope

Postgres 17 JSON_TABLE Streaming Projection Memory Envelope defines an industrial-grade behavioral standard for backend engineering. Governs SQL/JSON JSON_TABLE transformations in PostgreSQL 17 to eliminate backend worker out-of-memory termination during high-cardinality JSONB shredding. Mandates explicit typed projections, bounded nested path evaluations, and chunked cursor-driven ingestion to ensure transformations execute strictly within designated backend working memory limits. 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: Monolithic unpartitioned JSON_TABLE projections across unbounded JSONB datasets exhausting backend working memory and triggering OS OOM termination. 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 DriftMonolithic unpartitioned JSON_TABLE projections across unbounded JSONB datasets exhausting backend working memory and triggering OS OOM termination.Critical
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 bound JSON_TABLE input sets using indexed keyset pagination or chunked batch windows instead of executing whole-table unnested projections.

Engineers MUST ALWAYS bound JSON_TABLE input sets using indexed keyset pagination or chunked batch windows instead of executing whole-table unnested 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 projections using unqualified wildcard path expressions (e.g., '$.*') or unconstrained recursive descent ('$..*') on deep documents.

Engineers MUST NOT execute JSON_TABLE projections using unqualified wildcard path expressions (e.g., '$.*') or unconstrained recursive descent ('$..*') on deep documents.

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 SHOULD specify exact data types with strict size envelopes (e.g., VARCHAR(64), INT, NUMERIC) rather than unbounded TEXT or nested JSONB types in JSON_TABLE COLUMNS clauses.

Code SHOULD specify exact data types with strict size envelopes (e.g., VARCHAR(64), INT, NUMERIC) rather than unbounded TEXT or nested JSONB types in JSON_TABLE COLUMNS clauses.

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 enforce explicit error handling clauses ('ERROR ON ERROR' or 'EMPTY ON ERROR') in JSON_TABLE definitions to prevent silent memory-retaining error state accumulation.

Services MUST enforce explicit error handling clauses ('ERROR ON ERROR' or 'EMPTY ON ERROR') in JSON_TABLE definitions to prevent silent memory-retaining error state accumulation.

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 join high-cardinality lateral JSON_TABLE projections directly onto wide parent tables without an intermediate materialized CTE or temp table checkpoint.

Components NEVER join high-cardinality lateral JSON_TABLE projections directly onto wide parent tables without an intermediate materialized CTE or temp table checkpoint.

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 Streaming Projection Memory Envelope critical for AI coding assistants?

Governs SQL/JSON JSON_TABLE transformations in PostgreSQL 17 to eliminate backend worker out-of-memory termination during high-cardinality JSONB shredding. Mandates explicit typed projections, bounded nested path evaluations, and chunked cursor-driven ingestion to ensure transformations execute strictly within designated backend working memory limits. 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 (Monolithic unpartitioned JSON_TABLE projections across unbounded JSONB datasets exhausting backend working memory and triggering OS OOM termination.) 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