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-quota-standard

Postgres 17 JSON_TABLE Streamed Pipeline Memory Quotas

Enforces deterministic batching, streaming evaluation, and session-level work_mem guardrails when projecting large JSON/JSONB payloads using PostgreSQL 17 JSON_TABLE. Unbounded relational projections over high-throughput JSON collections cause intermediate palloc allocations inside backend memory contexts that bypass standard executor work_mem, culminating in postmaster backend OOM process termination. All JSON_TABLE queries targeting variable-size collections must bound row outputs via strict path predicates, avoid nested array projections in a single execution step, and run within controlled chunked transactions.

Prohibited Anti-Pattern: Unbounded JSON_TABLE Materialization Without Chunking or Memory Guardrails

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 JSON_TABLE Streamed Pipeline Memory Quotas - Enforces deterministic batching, streaming evaluation, and session-level work_mem guardrails when projecting large JSON/JSONB payloads using PostgreSQL 17 JSON_TABLE. Unbounded relational projections over high-throughput JSON collections cause intermediate palloc allocations inside backend memory contexts that bypass standard executor work_mem, culminating in postmaster backend OOM process termination. All JSON_TABLE queries targeting variable-size collections must bound row outputs via strict path predicates, avoid nested array projections in a single execution step, and run within controlled chunked transactions.
globs: src/repositories/**/*.ts, src/services/**/*.ts, src/database/**/*.ts, src/db/migrations/**/*.sql, src/db/queries/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-json-table-memory-quota-standard"
---

# Postgres 17 JSON_TABLE Streamed Pipeline Memory Quotas

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded JSON_TABLE Materialization Without Chunking or Memory Guardrails

## System Constraints
You are a Principal Database Architect enforcing strict memory and execution invariants for PostgreSQL 17 JSON_TABLE pipelines. You must prevent backend process OOM termination caused by excessive palloc accumulation during jsonpath projection of large or deeply nested JSON/JSONB payloads. You mandate batched cursoring, explicit work_mem tuning per query context, bounded array iteration, and memory-safe projection paths.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict LIMIT and pagination bounds at the source table level before passing JSONB payloads into JSON_TABLE.
- Engineers MUST NOT project unbounded wildcards (e.g., '$.items[*]') over multi-megabyte JSONB columns inside open-ended SELECT queries without keyset or cursor chunking.
- Services MUST execute intensive JSON_TABLE projections inside dedicated transactions with explicit local session overrides for 'work_mem' and statement timeouts.
- Code SHOULD prefer single-pass linear column projections and avoid NESTED PATH clauses on high-cardinality JSON arrays that force intermediate Cartesian cross-products in palloc memory contexts.
- Queries MUST filter out NULL or oversized payloads prior to invoking JSON_TABLE by utilizing functional GIN indexes or size checks (e.g., pg_column_size(json_col) < 1048576).

## Bad vs Good Implementations
### Unbounded JSON_TABLE Materialization vs. Streamed Keyset Batched Projection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This query joins every unprocessed row in raw_ingestion_log into an unbounded JSON_TABLE projection with a NESTED PATH. PostgreSQL allocates memory within the query execution context (palloc) for each expanded row; because JSON_TABLE operates inside expression evaluation, intermediate memory is not cleared until the node finishes, triggering backend OOM when processing large or numerous payloads.
```typescript
import { sql } from 'kysely';
import type { Database } from '../db/types';

export async function extractAuditEvents(db: Database): Promise<void> {
  // ANTI-PATTERN: Ingests all payloads simultaneously with an unbounded NESTED PATH.
  // Forces backend executor to allocate massive palloc buffers for intermediate relational sets,
  // leading to OOM crash (SIGKILL by OS OOM killer) under concurrent ingestion loads.
  await sql`
    SELECT j.event_id, j.action, j.timestamp, j.detail_key, j.detail_value
    FROM raw_ingestion_log r,
    JSON_TABLE(
      r.payload,
      '$.events[*]'
      COLUMNS (
        event_id text PATH '$.id',
        action text PATH '$.action',
        timestamp timestamptz PATH '$.timestamp',
        NESTED PATH '$.details[*]'
          COLUMNS (
            detail_key text PATH '$.key',
            detail_value text PATH '$.value'
          )
      )
    ) j
    WHERE r.processed = false;
  `.execute(db);
}
```

#### Production Standard (Correct)
> **Standard**: The production pattern sets deterministic boundary conditions: it enforces keyset pagination (id > lastId with LIMIT 500), isolates execution within a controlled transaction with scoped work_mem and timeouts, eliminates memory-multiplying NESTED PATH joins, and safeguards palloc limits by checking pg_column_size before invocation.
```typescript
import { sql } from 'kysely';
import type { Database } from '../db/types';

const BATCH_SIZE = 500;
const MAX_SAFE_JSON_BYTES = 524_288; // 512 KiB per payload limit for JSON_TABLE

export async function extractAuditEventsSafely(db: Database): Promise<void> {
  let lastId = 0;
  let hasMore = true;

  while (hasMore) {
    const rows = await db.transaction().execute(async (trx) => {
      // Bound session memory and query execution budget
      await sql`SET LOCAL work_mem = '32MB'`.execute(trx);
      await sql`SET LOCAL statement_timeout = '15s'`.execute(trx);

      return await sql<{
        event_id: string;
        action: string;
        timestamp: string;
        log_id: number;
      }>`
        SELECT 
          r.id AS log_id,
          j.event_id,
          j.action,
          j.timestamp
        FROM raw_ingestion_log r,
        JSON_TABLE(
          r.payload,
          '$.events[*]'
          COLUMNS (
            event_id text PATH '$.id',
            action text PATH '$.action',
            timestamp timestamptz PATH '$.timestamp'
          )
        ) j
        WHERE r.id > ${lastId}
          AND r.processed = false
          AND pg_column_size(r.payload) <= ${MAX_SAFE_JSON_BYTES}
        ORDER BY r.id ASC
        LIMIT ${BATCH_SIZE};
      `.execute(trx);
    });

    if (rows.rows.length === 0) {
      hasMore = false;
      break;
    }

    lastId = rows.rows[rows.rows.length - 1].log_id;
    // Process the streamed batch...
  }
}
```

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 Streamed Pipeline Memory Quotas

Postgres 17 JSON_TABLE Streamed Pipeline Memory Quotas defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic batching, streaming evaluation, and session-level work_mem guardrails when projecting large JSON/JSONB payloads using PostgreSQL 17 JSON_TABLE. Unbounded relational projections over high-throughput JSON collections cause intermediate palloc allocations inside backend memory contexts that bypass standard executor work_mem, culminating in postmaster backend OOM process termination. All JSON_TABLE queries targeting variable-size collections must bound row outputs via strict path predicates, avoid nested array projections in a single execution step, and run within controlled chunked transactions. 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 JSON_TABLE Materialization Without Chunking or Memory Guardrails 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 JSON_TABLE Materialization Without Chunking or Memory GuardrailsCritical
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 enforce strict LIMIT and pagination bounds at the source table level before passing JSONB payloads into JSON_TABLE.

Engineers MUST ALWAYS enforce strict LIMIT and pagination bounds at the source table level before passing JSONB payloads into JSON_TABLE.

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 project unbounded wildcards (e.g., '$.items[*]') over multi-megabyte JSONB columns inside open-ended SELECT queries without keyset or cursor chunking.

Engineers MUST NOT project unbounded wildcards (e.g., '$.items[*]') over multi-megabyte JSONB columns inside open-ended SELECT queries without 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

Services MUST execute intensive JSON_TABLE projections inside dedicated transactions with explicit local session overrides for 'work_mem' and statement timeouts.

Services MUST execute intensive JSON_TABLE projections inside dedicated transactions with explicit local session overrides for 'work_mem' and statement timeouts.

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 prefer single-pass linear column projections and avoid NESTED PATH clauses on high-cardinality JSON arrays that force intermediate Cartesian cross-products in palloc memory contexts.

Code SHOULD prefer single-pass linear column projections and avoid NESTED PATH clauses on high-cardinality JSON arrays that force intermediate Cartesian cross-products in palloc memory contexts.

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

Queries MUST filter out NULL or oversized payloads prior to invoking JSON_TABLE by utilizing functional GIN indexes or size checks (e.g., pg_column_size(json_col) < 1048576).

Queries MUST filter out NULL or oversized payloads prior to invoking JSON_TABLE by utilizing functional GIN indexes or size checks (e.g., pg_column_size(json_col) < 1048576).

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 Streamed Pipeline Memory Quotas critical for AI coding assistants?

Enforces deterministic batching, streaming evaluation, and session-level work_mem guardrails when projecting large JSON/JSONB payloads using PostgreSQL 17 JSON_TABLE. Unbounded relational projections over high-throughput JSON collections cause intermediate palloc allocations inside backend memory contexts that bypass standard executor work_mem, culminating in postmaster backend OOM process termination. All JSON_TABLE queries targeting variable-size collections must bound row outputs via strict path predicates, avoid nested array projections in a single execution step, and run within controlled chunked transactions. 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 JSON_TABLE Materialization Without Chunking or Memory Guardrails) 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